es6.js 4.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216982179821898219982209822198222982239822498225982269822798228982299823098231982329823398234982359823698237982389823998240982419824298243982449824598246982479824898249982509825198252982539825498255982569825798258982599826098261982629826398264982659826698267982689826998270982719827298273982749827598276982779827898279982809828198282982839828498285982869828798288982899829098291982929829398294982959829698297982989829998300983019830298303983049830598306983079830898309983109831198312983139831498315983169831798318983199832098321983229832398324983259832698327983289832998330983319833298333983349833598336983379833898339983409834198342983439834498345983469834798348983499835098351983529835398354983559835698357983589835998360983619836298363983649836598366983679836898369983709837198372983739837498375983769837798378983799838098381983829838398384983859838698387983889838998390983919839298393983949839598396983979839898399984009840198402984039840498405984069840798408984099841098411984129841398414984159841698417984189841998420984219842298423984249842598426984279842898429984309843198432984339843498435984369843798438984399844098441984429844398444984459844698447984489844998450984519845298453984549845598456984579845898459984609846198462984639846498465984669846798468984699847098471984729847398474984759847698477984789847998480984819848298483984849848598486984879848898489984909849198492984939849498495984969849798498984999850098501985029850398504985059850698507985089850998510985119851298513985149851598516985179851898519985209852198522985239852498525985269852798528985299853098531985329853398534985359853698537985389853998540985419854298543985449854598546
  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. _this.skipOnPointerObservable = false;
  1342. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1343. return _this;
  1344. }
  1345. return PointerInfoPre;
  1346. }(PointerInfoBase));
  1347. BABYLON.PointerInfoPre = PointerInfoPre;
  1348. /**
  1349. * This type contains all the data related to a pointer event in Babylon.js.
  1350. * 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.
  1351. */
  1352. var PointerInfo = /** @class */ (function (_super) {
  1353. __extends(PointerInfo, _super);
  1354. function PointerInfo(type, event, pickInfo) {
  1355. var _this = _super.call(this, type, event) || this;
  1356. _this.pickInfo = pickInfo;
  1357. return _this;
  1358. }
  1359. return PointerInfo;
  1360. }(PointerInfoBase));
  1361. BABYLON.PointerInfo = PointerInfo;
  1362. })(BABYLON || (BABYLON = {}));
  1363. //# sourceMappingURL=babylon.pointerEvents.js.map
  1364. var BABYLON;
  1365. (function (BABYLON) {
  1366. BABYLON.ToGammaSpace = 1 / 2.2;
  1367. BABYLON.ToLinearSpace = 2.2;
  1368. BABYLON.Epsilon = 0.001;
  1369. /**
  1370. * Class used to hold a RBG color
  1371. */
  1372. var Color3 = /** @class */ (function () {
  1373. /**
  1374. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1375. * @param r defines the red component (between 0 and 1, default is 0)
  1376. * @param g defines the green component (between 0 and 1, default is 0)
  1377. * @param b defines the blue component (between 0 and 1, default is 0)
  1378. */
  1379. function Color3(
  1380. /**
  1381. * Defines the red component (between 0 and 1, default is 0)
  1382. */
  1383. r,
  1384. /**
  1385. * Defines the green component (between 0 and 1, default is 0)
  1386. */
  1387. g,
  1388. /**
  1389. * Defines the blue component (between 0 and 1, default is 0)
  1390. */
  1391. b) {
  1392. if (r === void 0) { r = 0; }
  1393. if (g === void 0) { g = 0; }
  1394. if (b === void 0) { b = 0; }
  1395. this.r = r;
  1396. this.g = g;
  1397. this.b = b;
  1398. }
  1399. /**
  1400. * Creates a string with the Color3 current values
  1401. * @returns the string representation of the Color3 object
  1402. */
  1403. Color3.prototype.toString = function () {
  1404. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1405. };
  1406. /**
  1407. * Returns the string "Color3"
  1408. * @returns "Color3"
  1409. */
  1410. Color3.prototype.getClassName = function () {
  1411. return "Color3";
  1412. };
  1413. /**
  1414. * Compute the Color3 hash code
  1415. * @returns an unique number that can be used to hash Color3 objects
  1416. */
  1417. Color3.prototype.getHashCode = function () {
  1418. var hash = this.r || 0;
  1419. hash = (hash * 397) ^ (this.g || 0);
  1420. hash = (hash * 397) ^ (this.b || 0);
  1421. return hash;
  1422. };
  1423. // Operators
  1424. /**
  1425. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1426. * @param array defines the array where to store the r,g,b components
  1427. * @param index defines an optional index in the target array to define where to start storing values
  1428. * @returns the current Color3 object
  1429. */
  1430. Color3.prototype.toArray = function (array, index) {
  1431. if (index === undefined) {
  1432. index = 0;
  1433. }
  1434. array[index] = this.r;
  1435. array[index + 1] = this.g;
  1436. array[index + 2] = this.b;
  1437. return this;
  1438. };
  1439. /**
  1440. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1441. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1442. * @returns a new {BABYLON.Color4} object
  1443. */
  1444. Color3.prototype.toColor4 = function (alpha) {
  1445. if (alpha === void 0) { alpha = 1; }
  1446. return new Color4(this.r, this.g, this.b, alpha);
  1447. };
  1448. /**
  1449. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1450. * @returns the new array
  1451. */
  1452. Color3.prototype.asArray = function () {
  1453. var result = new Array();
  1454. this.toArray(result, 0);
  1455. return result;
  1456. };
  1457. /**
  1458. * Returns the luminance value
  1459. * @returns a float value
  1460. */
  1461. Color3.prototype.toLuminance = function () {
  1462. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1463. };
  1464. /**
  1465. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1466. * @param otherColor defines the second operand
  1467. * @returns the new Color3 object
  1468. */
  1469. Color3.prototype.multiply = function (otherColor) {
  1470. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1471. };
  1472. /**
  1473. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1474. * @param otherColor defines the second operand
  1475. * @param result defines the Color3 object where to store the result
  1476. * @returns the current Color3
  1477. */
  1478. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1479. result.r = this.r * otherColor.r;
  1480. result.g = this.g * otherColor.g;
  1481. result.b = this.b * otherColor.b;
  1482. return this;
  1483. };
  1484. /**
  1485. * Determines equality between Color3 objects
  1486. * @param otherColor defines the second operand
  1487. * @returns true if the rgb values are equal to the given ones
  1488. */
  1489. Color3.prototype.equals = function (otherColor) {
  1490. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1491. };
  1492. /**
  1493. * Determines equality between the current Color3 object and a set of r,b,g values
  1494. * @param r defines the red component to check
  1495. * @param g defines the green component to check
  1496. * @param b defines the blue component to check
  1497. * @returns true if the rgb values are equal to the given ones
  1498. */
  1499. Color3.prototype.equalsFloats = function (r, g, b) {
  1500. return this.r === r && this.g === g && this.b === b;
  1501. };
  1502. /**
  1503. * Multiplies in place each rgb value by scale
  1504. * @param scale defines the scaling factor
  1505. * @returns the updated Color3
  1506. */
  1507. Color3.prototype.scale = function (scale) {
  1508. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1509. };
  1510. /**
  1511. * Multiplies the rgb values by scale and stores the result into "result"
  1512. * @param scale defines the scaling factor
  1513. * @param result defines the Color3 object where to store the result
  1514. * @returns the unmodified current Color3
  1515. */
  1516. Color3.prototype.scaleToRef = function (scale, result) {
  1517. result.r = this.r * scale;
  1518. result.g = this.g * scale;
  1519. result.b = this.b * scale;
  1520. return this;
  1521. };
  1522. /**
  1523. * Scale the current Color3 values by a factor and add the result to a given Color3
  1524. * @param scale defines the scale factor
  1525. * @param result defines color to store the result into
  1526. * @returns the unmodified current Color3
  1527. */
  1528. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1529. result.r += this.r * scale;
  1530. result.g += this.g * scale;
  1531. result.b += this.b * scale;
  1532. return this;
  1533. };
  1534. /**
  1535. * Clamps the rgb values by the min and max values and stores the result into "result"
  1536. * @param min defines minimum clamping value (default is 0)
  1537. * @param max defines maximum clamping value (default is 1)
  1538. * @param result defines color to store the result into
  1539. * @returns the original Color3
  1540. */
  1541. Color3.prototype.clampToRef = function (min, max, result) {
  1542. if (min === void 0) { min = 0; }
  1543. if (max === void 0) { max = 1; }
  1544. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1545. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1546. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1547. return this;
  1548. };
  1549. /**
  1550. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1551. * @param otherColor defines the second operand
  1552. * @returns the new Color3
  1553. */
  1554. Color3.prototype.add = function (otherColor) {
  1555. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1556. };
  1557. /**
  1558. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1559. * @param otherColor defines the second operand
  1560. * @param result defines Color3 object to store the result into
  1561. * @returns the unmodified current Color3
  1562. */
  1563. Color3.prototype.addToRef = function (otherColor, result) {
  1564. result.r = this.r + otherColor.r;
  1565. result.g = this.g + otherColor.g;
  1566. result.b = this.b + otherColor.b;
  1567. return this;
  1568. };
  1569. /**
  1570. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3
  1573. */
  1574. Color3.prototype.subtract = function (otherColor) {
  1575. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1576. };
  1577. /**
  1578. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines Color3 object to store the result into
  1581. * @returns the unmodified current Color3
  1582. */
  1583. Color3.prototype.subtractToRef = function (otherColor, result) {
  1584. result.r = this.r - otherColor.r;
  1585. result.g = this.g - otherColor.g;
  1586. result.b = this.b - otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Copy the current object
  1591. * @returns a new Color3 copied the current one
  1592. */
  1593. Color3.prototype.clone = function () {
  1594. return new Color3(this.r, this.g, this.b);
  1595. };
  1596. /**
  1597. * Copies the rgb values from the source in the current Color3
  1598. * @param source defines the source Color3 object
  1599. * @returns the updated Color3 object
  1600. */
  1601. Color3.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. return this;
  1606. };
  1607. /**
  1608. * Updates the Color3 rgb values from the given floats
  1609. * @param r defines the red component to read from
  1610. * @param g defines the green component to read from
  1611. * @param b defines the blue component to read from
  1612. * @returns the current Color3 object
  1613. */
  1614. Color3.prototype.copyFromFloats = function (r, g, b) {
  1615. this.r = r;
  1616. this.g = g;
  1617. this.b = b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Updates the Color3 rgb values from the given floats
  1622. * @param r defines the red component to read from
  1623. * @param g defines the green component to read from
  1624. * @param b defines the blue component to read from
  1625. * @returns the current Color3 object
  1626. */
  1627. Color3.prototype.set = function (r, g, b) {
  1628. return this.copyFromFloats(r, g, b);
  1629. };
  1630. /**
  1631. * Compute the Color3 hexadecimal code as a string
  1632. * @returns a string containing the hexadecimal representation of the Color3 object
  1633. */
  1634. Color3.prototype.toHexString = function () {
  1635. var intR = (this.r * 255) | 0;
  1636. var intG = (this.g * 255) | 0;
  1637. var intB = (this.b * 255) | 0;
  1638. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1639. };
  1640. /**
  1641. * Computes a new Color3 converted from the current one to linear space
  1642. * @returns a new Color3 object
  1643. */
  1644. Color3.prototype.toLinearSpace = function () {
  1645. var convertedColor = new Color3();
  1646. this.toLinearSpaceToRef(convertedColor);
  1647. return convertedColor;
  1648. };
  1649. /**
  1650. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1651. * @param convertedColor defines the Color3 object where to store the linear space version
  1652. * @returns the unmodified Color3
  1653. */
  1654. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1655. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1656. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1657. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1658. return this;
  1659. };
  1660. /**
  1661. * Computes a new Color3 converted from the current one to gamma space
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.prototype.toGammaSpace = function () {
  1665. var convertedColor = new Color3();
  1666. this.toGammaSpaceToRef(convertedColor);
  1667. return convertedColor;
  1668. };
  1669. /**
  1670. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1671. * @param convertedColor defines the Color3 object where to store the gamma space version
  1672. * @returns the unmodified Color3
  1673. */
  1674. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1675. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1676. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1677. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1678. return this;
  1679. };
  1680. // Statics
  1681. /**
  1682. * Creates a new Color3 from the string containing valid hexadecimal values
  1683. * @param hex defines a string containing valid hexadecimal values
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.FromHexString = function (hex) {
  1687. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1688. return new Color3(0, 0, 0);
  1689. }
  1690. var r = parseInt(hex.substring(1, 3), 16);
  1691. var g = parseInt(hex.substring(3, 5), 16);
  1692. var b = parseInt(hex.substring(5, 7), 16);
  1693. return Color3.FromInts(r, g, b);
  1694. };
  1695. /**
  1696. * Creates a new Vector3 from the starting index of the given array
  1697. * @param array defines the source array
  1698. * @param offset defines an offset in the source array
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.FromArray = function (array, offset) {
  1702. if (offset === void 0) { offset = 0; }
  1703. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1704. };
  1705. /**
  1706. * Creates a new Color3 from integer values (< 256)
  1707. * @param r defines the red component to read from (value between 0 and 255)
  1708. * @param g defines the green component to read from (value between 0 and 255)
  1709. * @param b defines the blue component to read from (value between 0 and 255)
  1710. * @returns a new Color3 object
  1711. */
  1712. Color3.FromInts = function (r, g, b) {
  1713. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1714. };
  1715. /**
  1716. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1717. * @param start defines the start Color3 value
  1718. * @param end defines the end Color3 value
  1719. * @param amount defines the gradient value between start and end
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.Lerp = function (start, end, amount) {
  1723. var r = start.r + ((end.r - start.r) * amount);
  1724. var g = start.g + ((end.g - start.g) * amount);
  1725. var b = start.b + ((end.b - start.b) * amount);
  1726. return new Color3(r, g, b);
  1727. };
  1728. /**
  1729. * Returns a Color3 value containing a red color
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.Red = function () { return new Color3(1, 0, 0); };
  1733. /**
  1734. * Returns a Color3 value containing a green color
  1735. * @returns a new Color3 object
  1736. */
  1737. Color3.Green = function () { return new Color3(0, 1, 0); };
  1738. /**
  1739. * Returns a Color3 value containing a blue color
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1743. /**
  1744. * Returns a Color3 value containing a black color
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.Black = function () { return new Color3(0, 0, 0); };
  1748. /**
  1749. * Returns a Color3 value containing a white color
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.White = function () { return new Color3(1, 1, 1); };
  1753. /**
  1754. * Returns a Color3 value containing a purple color
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1758. /**
  1759. * Returns a Color3 value containing a magenta color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1763. /**
  1764. * Returns a Color3 value containing a yellow color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a gray color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1773. /**
  1774. * Returns a Color3 value containing a teal color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1778. /**
  1779. * Returns a Color3 value containing a random color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1783. return Color3;
  1784. }());
  1785. BABYLON.Color3 = Color3;
  1786. /**
  1787. * Class used to hold a RBGA color
  1788. */
  1789. var Color4 = /** @class */ (function () {
  1790. /**
  1791. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1792. * @param r defines the red component (between 0 and 1, default is 0)
  1793. * @param g defines the green component (between 0 and 1, default is 0)
  1794. * @param b defines the blue component (between 0 and 1, default is 0)
  1795. * @param a defines the alpha component (between 0 and 1, default is 1)
  1796. */
  1797. function Color4(
  1798. /**
  1799. * Defines the red component (between 0 and 1, default is 0)
  1800. */
  1801. r,
  1802. /**
  1803. * Defines the green component (between 0 and 1, default is 0)
  1804. */
  1805. g,
  1806. /**
  1807. * Defines the blue component (between 0 and 1, default is 0)
  1808. */
  1809. b,
  1810. /**
  1811. * Defines the alpha component (between 0 and 1, default is 1)
  1812. */
  1813. a) {
  1814. if (r === void 0) { r = 0; }
  1815. if (g === void 0) { g = 0; }
  1816. if (b === void 0) { b = 0; }
  1817. if (a === void 0) { a = 1; }
  1818. this.r = r;
  1819. this.g = g;
  1820. this.b = b;
  1821. this.a = a;
  1822. }
  1823. // Operators
  1824. /**
  1825. * Adds in place the given Color4 values to the current Color4 object
  1826. * @param right defines the second operand
  1827. * @returns the current updated Color4 object
  1828. */
  1829. Color4.prototype.addInPlace = function (right) {
  1830. this.r += right.r;
  1831. this.g += right.g;
  1832. this.b += right.b;
  1833. this.a += right.a;
  1834. return this;
  1835. };
  1836. /**
  1837. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1838. * @returns the new array
  1839. */
  1840. Color4.prototype.asArray = function () {
  1841. var result = new Array();
  1842. this.toArray(result, 0);
  1843. return result;
  1844. };
  1845. /**
  1846. * Stores from the starting index in the given array the Color4 successive values
  1847. * @param array defines the array where to store the r,g,b components
  1848. * @param index defines an optional index in the target array to define where to start storing values
  1849. * @returns the current Color4 object
  1850. */
  1851. Color4.prototype.toArray = function (array, index) {
  1852. if (index === undefined) {
  1853. index = 0;
  1854. }
  1855. array[index] = this.r;
  1856. array[index + 1] = this.g;
  1857. array[index + 2] = this.b;
  1858. array[index + 3] = this.a;
  1859. return this;
  1860. };
  1861. /**
  1862. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1863. * @param right defines the second operand
  1864. * @returns a new Color4 object
  1865. */
  1866. Color4.prototype.add = function (right) {
  1867. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1868. };
  1869. /**
  1870. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1871. * @param right defines the second operand
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.subtract = function (right) {
  1875. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1876. };
  1877. /**
  1878. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1879. * @param right defines the second operand
  1880. * @param result defines the Color4 object where to store the result
  1881. * @returns the current Color4 object
  1882. */
  1883. Color4.prototype.subtractToRef = function (right, result) {
  1884. result.r = this.r - right.r;
  1885. result.g = this.g - right.g;
  1886. result.b = this.b - right.b;
  1887. result.a = this.a - right.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new Color4 with the current Color4 values multiplied by scale
  1892. * @param scale defines the scaling factor to apply
  1893. * @returns a new Color4 object
  1894. */
  1895. Color4.prototype.scale = function (scale) {
  1896. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1897. };
  1898. /**
  1899. * Multiplies the current Color4 values by scale and stores the result in "result"
  1900. * @param scale defines the scaling factor to apply
  1901. * @param result defines the Color4 object where to store the result
  1902. * @returns the current unmodified Color4
  1903. */
  1904. Color4.prototype.scaleToRef = function (scale, result) {
  1905. result.r = this.r * scale;
  1906. result.g = this.g * scale;
  1907. result.b = this.b * scale;
  1908. result.a = this.a * scale;
  1909. return this;
  1910. };
  1911. /**
  1912. * Scale the current Color4 values by a factor and add the result to a given Color4
  1913. * @param scale defines the scale factor
  1914. * @param result defines the Color4 object where to store the result
  1915. * @returns the unmodified current Color4
  1916. */
  1917. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1918. result.r += this.r * scale;
  1919. result.g += this.g * scale;
  1920. result.b += this.b * scale;
  1921. result.a += this.a * scale;
  1922. return this;
  1923. };
  1924. /**
  1925. * Clamps the rgb values by the min and max values and stores the result into "result"
  1926. * @param min defines minimum clamping value (default is 0)
  1927. * @param max defines maximum clamping value (default is 1)
  1928. * @param result defines color to store the result into.
  1929. * @returns the cuurent Color4
  1930. */
  1931. Color4.prototype.clampToRef = function (min, max, result) {
  1932. if (min === void 0) { min = 0; }
  1933. if (max === void 0) { max = 1; }
  1934. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1935. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1936. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1937. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1938. return this;
  1939. };
  1940. /**
  1941. * Multipy an Color4 value by another and return a new Color4 object
  1942. * @param color defines the Color4 value to multiply by
  1943. * @returns a new Color4 object
  1944. */
  1945. Color4.prototype.multiply = function (color) {
  1946. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1947. };
  1948. /**
  1949. * Multipy a Color4 value by another and push the result in a reference value
  1950. * @param color defines the Color4 value to multiply by
  1951. * @param result defines the Color4 to fill the result in
  1952. * @returns the result Color4
  1953. */
  1954. Color4.prototype.multiplyToRef = function (color, result) {
  1955. result.r = this.r * color.r;
  1956. result.g = this.g * color.g;
  1957. result.b = this.b * color.b;
  1958. result.a = this.a * color.a;
  1959. return result;
  1960. };
  1961. /**
  1962. * Creates a string with the Color4 current values
  1963. * @returns the string representation of the Color4 object
  1964. */
  1965. Color4.prototype.toString = function () {
  1966. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1967. };
  1968. /**
  1969. * Returns the string "Color4"
  1970. * @returns "Color4"
  1971. */
  1972. Color4.prototype.getClassName = function () {
  1973. return "Color4";
  1974. };
  1975. /**
  1976. * Compute the Color4 hash code
  1977. * @returns an unique number that can be used to hash Color4 objects
  1978. */
  1979. Color4.prototype.getHashCode = function () {
  1980. var hash = this.r || 0;
  1981. hash = (hash * 397) ^ (this.g || 0);
  1982. hash = (hash * 397) ^ (this.b || 0);
  1983. hash = (hash * 397) ^ (this.a || 0);
  1984. return hash;
  1985. };
  1986. /**
  1987. * Creates a new Color4 copied from the current one
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.clone = function () {
  1991. return new Color4(this.r, this.g, this.b, this.a);
  1992. };
  1993. /**
  1994. * Copies the given Color4 values into the current one
  1995. * @param source defines the source Color4 object
  1996. * @returns the current updated Color4 object
  1997. */
  1998. Color4.prototype.copyFrom = function (source) {
  1999. this.r = source.r;
  2000. this.g = source.g;
  2001. this.b = source.b;
  2002. this.a = source.a;
  2003. return this;
  2004. };
  2005. /**
  2006. * Copies the given float values into the current one
  2007. * @param r defines the red component to read from
  2008. * @param g defines the green component to read from
  2009. * @param b defines the blue component to read from
  2010. * @param a defines the alpha component to read from
  2011. * @returns the current updated Color4 object
  2012. */
  2013. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2014. this.r = r;
  2015. this.g = g;
  2016. this.b = b;
  2017. this.a = a;
  2018. return this;
  2019. };
  2020. /**
  2021. * Copies the given float values into the current one
  2022. * @param r defines the red component to read from
  2023. * @param g defines the green component to read from
  2024. * @param b defines the blue component to read from
  2025. * @param a defines the alpha component to read from
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.set = function (r, g, b, a) {
  2029. return this.copyFromFloats(r, g, b, a);
  2030. };
  2031. /**
  2032. * Compute the Color4 hexadecimal code as a string
  2033. * @returns a string containing the hexadecimal representation of the Color4 object
  2034. */
  2035. Color4.prototype.toHexString = function () {
  2036. var intR = (this.r * 255) | 0;
  2037. var intG = (this.g * 255) | 0;
  2038. var intB = (this.b * 255) | 0;
  2039. var intA = (this.a * 255) | 0;
  2040. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2041. };
  2042. /**
  2043. * Computes a new Color4 converted from the current one to linear space
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.prototype.toLinearSpace = function () {
  2047. var convertedColor = new Color4();
  2048. this.toLinearSpaceToRef(convertedColor);
  2049. return convertedColor;
  2050. };
  2051. /**
  2052. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2053. * @param convertedColor defines the Color4 object where to store the linear space version
  2054. * @returns the unmodified Color4
  2055. */
  2056. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2057. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2058. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2059. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2060. convertedColor.a = this.a;
  2061. return this;
  2062. };
  2063. /**
  2064. * Computes a new Color4 converted from the current one to gamma space
  2065. * @returns a new Color4 object
  2066. */
  2067. Color4.prototype.toGammaSpace = function () {
  2068. var convertedColor = new Color4();
  2069. this.toGammaSpaceToRef(convertedColor);
  2070. return convertedColor;
  2071. };
  2072. /**
  2073. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2074. * @param convertedColor defines the Color4 object where to store the gamma space version
  2075. * @returns the unmodified Color4
  2076. */
  2077. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2078. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2079. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2080. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2081. convertedColor.a = this.a;
  2082. return this;
  2083. };
  2084. // Statics
  2085. /**
  2086. * Creates a new Color4 from the string containing valid hexadecimal values
  2087. * @param hex defines a string containing valid hexadecimal values
  2088. * @returns a new Color4 object
  2089. */
  2090. Color4.FromHexString = function (hex) {
  2091. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2092. return new Color4(0.0, 0.0, 0.0, 0.0);
  2093. }
  2094. var r = parseInt(hex.substring(1, 3), 16);
  2095. var g = parseInt(hex.substring(3, 5), 16);
  2096. var b = parseInt(hex.substring(5, 7), 16);
  2097. var a = parseInt(hex.substring(7, 9), 16);
  2098. return Color4.FromInts(r, g, b, a);
  2099. };
  2100. /**
  2101. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2102. * @param left defines the start value
  2103. * @param right defines the end value
  2104. * @param amount defines the gradient factor
  2105. * @returns a new Color4 object
  2106. */
  2107. Color4.Lerp = function (left, right, amount) {
  2108. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2109. Color4.LerpToRef(left, right, amount, result);
  2110. return result;
  2111. };
  2112. /**
  2113. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2114. * @param left defines the start value
  2115. * @param right defines the end value
  2116. * @param amount defines the gradient factor
  2117. * @param result defines the Color4 object where to store data
  2118. */
  2119. Color4.LerpToRef = function (left, right, amount, result) {
  2120. result.r = left.r + (right.r - left.r) * amount;
  2121. result.g = left.g + (right.g - left.g) * amount;
  2122. result.b = left.b + (right.b - left.b) * amount;
  2123. result.a = left.a + (right.a - left.a) * amount;
  2124. };
  2125. /**
  2126. * Creates a new Color4 from the starting index element of the given array
  2127. * @param array defines the source array to read from
  2128. * @param offset defines the offset in the source array
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromArray = function (array, offset) {
  2132. if (offset === void 0) { offset = 0; }
  2133. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2134. };
  2135. /**
  2136. * Creates a new Color3 from integer values (< 256)
  2137. * @param r defines the red component to read from (value between 0 and 255)
  2138. * @param g defines the green component to read from (value between 0 and 255)
  2139. * @param b defines the blue component to read from (value between 0 and 255)
  2140. * @param a defines the alpha component to read from (value between 0 and 255)
  2141. * @returns a new Color3 object
  2142. */
  2143. Color4.FromInts = function (r, g, b, a) {
  2144. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2145. };
  2146. /**
  2147. * Check the content of a given array and convert it to an array containing RGBA data
  2148. * If the original array was already containing count * 4 values then it is returned directly
  2149. * @param colors defines the array to check
  2150. * @param count defines the number of RGBA data to expect
  2151. * @returns an array containing count * 4 values (RGBA)
  2152. */
  2153. Color4.CheckColors4 = function (colors, count) {
  2154. // Check if color3 was used
  2155. if (colors.length === count * 3) {
  2156. var colors4 = [];
  2157. for (var index = 0; index < colors.length; index += 3) {
  2158. var newIndex = (index / 3) * 4;
  2159. colors4[newIndex] = colors[index];
  2160. colors4[newIndex + 1] = colors[index + 1];
  2161. colors4[newIndex + 2] = colors[index + 2];
  2162. colors4[newIndex + 3] = 1.0;
  2163. }
  2164. return colors4;
  2165. }
  2166. return colors;
  2167. };
  2168. return Color4;
  2169. }());
  2170. BABYLON.Color4 = Color4;
  2171. /**
  2172. * Class representing a vector containing 2 coordinates
  2173. */
  2174. var Vector2 = /** @class */ (function () {
  2175. /**
  2176. * Creates a new Vector2 from the given x and y coordinates
  2177. * @param x defines the first coordinate
  2178. * @param y defines the second coordinate
  2179. */
  2180. function Vector2(
  2181. /** defines the first coordinate */
  2182. x,
  2183. /** defines the second coordinate */
  2184. y) {
  2185. this.x = x;
  2186. this.y = y;
  2187. }
  2188. /**
  2189. * Gets a string with the Vector2 coordinates
  2190. * @returns a string with the Vector2 coordinates
  2191. */
  2192. Vector2.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + "}";
  2194. };
  2195. /**
  2196. * Gets class name
  2197. * @returns the string "Vector2"
  2198. */
  2199. Vector2.prototype.getClassName = function () {
  2200. return "Vector2";
  2201. };
  2202. /**
  2203. * Gets current vector hash code
  2204. * @returns the Vector2 hash code as a number
  2205. */
  2206. Vector2.prototype.getHashCode = function () {
  2207. var hash = this.x || 0;
  2208. hash = (hash * 397) ^ (this.y || 0);
  2209. return hash;
  2210. };
  2211. // Operators
  2212. /**
  2213. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2214. * @param array defines the source array
  2215. * @param index defines the offset in source array
  2216. * @returns the current Vector2
  2217. */
  2218. Vector2.prototype.toArray = function (array, index) {
  2219. if (index === void 0) { index = 0; }
  2220. array[index] = this.x;
  2221. array[index + 1] = this.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Copy the current vector to an array
  2226. * @returns a new array with 2 elements: the Vector2 coordinates.
  2227. */
  2228. Vector2.prototype.asArray = function () {
  2229. var result = new Array();
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2235. * @param source defines the source Vector2
  2236. * @returns the current updated Vector2
  2237. */
  2238. Vector2.prototype.copyFrom = function (source) {
  2239. this.x = source.x;
  2240. this.y = source.y;
  2241. return this;
  2242. };
  2243. /**
  2244. * Sets the Vector2 coordinates with the given floats
  2245. * @param x defines the first coordinate
  2246. * @param y defines the second coordinate
  2247. * @returns the current updated Vector2
  2248. */
  2249. Vector2.prototype.copyFromFloats = function (x, y) {
  2250. this.x = x;
  2251. this.y = y;
  2252. return this;
  2253. };
  2254. /**
  2255. * Sets the Vector2 coordinates with the given floats
  2256. * @param x defines the first coordinate
  2257. * @param y defines the second coordinate
  2258. * @returns the current updated Vector2
  2259. */
  2260. Vector2.prototype.set = function (x, y) {
  2261. return this.copyFromFloats(x, y);
  2262. };
  2263. /**
  2264. * Add another vector with the current one
  2265. * @param otherVector defines the other vector
  2266. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2267. */
  2268. Vector2.prototype.add = function (otherVector) {
  2269. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2270. };
  2271. /**
  2272. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2273. * @param otherVector defines the other vector
  2274. * @param result defines the target vector
  2275. * @returns the unmodified current Vector2
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2284. * @param otherVector defines the other vector
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.addInPlace = function (otherVector) {
  2288. this.x += otherVector.x;
  2289. this.y += otherVector.y;
  2290. return this;
  2291. };
  2292. /**
  2293. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2294. * @param otherVector defines the other vector
  2295. * @returns a new Vector2
  2296. */
  2297. Vector2.prototype.addVector3 = function (otherVector) {
  2298. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2299. };
  2300. /**
  2301. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2302. * @param otherVector defines the other vector
  2303. * @returns a new Vector2
  2304. */
  2305. Vector2.prototype.subtract = function (otherVector) {
  2306. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2307. };
  2308. /**
  2309. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2310. * @param otherVector defines the other vector
  2311. * @param result defines the target vector
  2312. * @returns the unmodified current Vector2
  2313. */
  2314. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2315. result.x = this.x - otherVector.x;
  2316. result.y = this.y - otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns the current updated Vector2
  2323. */
  2324. Vector2.prototype.subtractInPlace = function (otherVector) {
  2325. this.x -= otherVector.x;
  2326. this.y -= otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Multiplies in place the current Vector2 coordinates by the given ones
  2331. * @param otherVector defines the other vector
  2332. * @returns the current updated Vector2
  2333. */
  2334. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2335. this.x *= otherVector.x;
  2336. this.y *= otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2341. * @param otherVector defines the other vector
  2342. * @returns a new Vector2
  2343. */
  2344. Vector2.prototype.multiply = function (otherVector) {
  2345. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2346. };
  2347. /**
  2348. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2349. * @param otherVector defines the other vector
  2350. * @param result defines the target vector
  2351. * @returns the unmodified current Vector2
  2352. */
  2353. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2354. result.x = this.x * otherVector.x;
  2355. result.y = this.y * otherVector.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.multiplyByFloats = function (x, y) {
  2365. return new Vector2(this.x * x, this.y * y);
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2369. * @param otherVector defines the other vector
  2370. * @returns a new Vector2
  2371. */
  2372. Vector2.prototype.divide = function (otherVector) {
  2373. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2374. };
  2375. /**
  2376. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2377. * @param otherVector defines the other vector
  2378. * @param result defines the target vector
  2379. * @returns the unmodified current Vector2
  2380. */
  2381. Vector2.prototype.divideToRef = function (otherVector, result) {
  2382. result.x = this.x / otherVector.x;
  2383. result.y = this.y / otherVector.y;
  2384. return this;
  2385. };
  2386. /**
  2387. * Divides the current Vector3 coordinates by the given ones
  2388. * @param otherVector defines the other vector
  2389. * @returns the current updated Vector2
  2390. */
  2391. Vector2.prototype.divideInPlace = function (otherVector) {
  2392. return this.divideToRef(otherVector, this);
  2393. };
  2394. /**
  2395. * Gets a new Vector2 with current Vector2 negated coordinates
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.negate = function () {
  2399. return new Vector2(-this.x, -this.y);
  2400. };
  2401. /**
  2402. * Multiply the Vector2 coordinates by scale
  2403. * @param scale defines the scaling factor
  2404. * @returns the current updated Vector2
  2405. */
  2406. Vector2.prototype.scaleInPlace = function (scale) {
  2407. this.x *= scale;
  2408. this.y *= scale;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2413. * @param scale defines the scaling factor
  2414. * @returns a new Vector2
  2415. */
  2416. Vector2.prototype.scale = function (scale) {
  2417. var result = new Vector2(0, 0);
  2418. this.scaleToRef(scale, result);
  2419. return result;
  2420. };
  2421. /**
  2422. * Scale the current Vector2 values by a factor to a given Vector2
  2423. * @param scale defines the scale factor
  2424. * @param result defines the Vector2 object where to store the result
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.scaleToRef = function (scale, result) {
  2428. result.x = this.x * scale;
  2429. result.y = this.y * scale;
  2430. return this;
  2431. };
  2432. /**
  2433. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2434. * @param scale defines the scale factor
  2435. * @param result defines the Vector2 object where to store the result
  2436. * @returns the unmodified current Vector2
  2437. */
  2438. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2439. result.x += this.x * scale;
  2440. result.y += this.y * scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Gets a boolean if two vectors are equals
  2445. * @param otherVector defines the other vector
  2446. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2447. */
  2448. Vector2.prototype.equals = function (otherVector) {
  2449. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2450. };
  2451. /**
  2452. * Gets a boolean if two vectors are equals (using an epsilon value)
  2453. * @param otherVector defines the other vector
  2454. * @param epsilon defines the minimal distance to consider equality
  2455. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2456. */
  2457. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2458. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2459. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2460. };
  2461. // Properties
  2462. /**
  2463. * Gets the length of the vector
  2464. * @returns the vector length (float)
  2465. */
  2466. Vector2.prototype.length = function () {
  2467. return Math.sqrt(this.x * this.x + this.y * this.y);
  2468. };
  2469. /**
  2470. * Gets the vector squared length
  2471. * @returns the vector squared length (float)
  2472. */
  2473. Vector2.prototype.lengthSquared = function () {
  2474. return (this.x * this.x + this.y * this.y);
  2475. };
  2476. // Methods
  2477. /**
  2478. * Normalize the vector
  2479. * @returns the current updated Vector2
  2480. */
  2481. Vector2.prototype.normalize = function () {
  2482. var len = this.length();
  2483. if (len === 0)
  2484. return this;
  2485. var num = 1.0 / len;
  2486. this.x *= num;
  2487. this.y *= num;
  2488. return this;
  2489. };
  2490. /**
  2491. * Gets a new Vector2 copied from the Vector2
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.clone = function () {
  2495. return new Vector2(this.x, this.y);
  2496. };
  2497. // Statics
  2498. /**
  2499. * Gets a new Vector2(0, 0)
  2500. * @returns a new Vector2
  2501. */
  2502. Vector2.Zero = function () {
  2503. return new Vector2(0, 0);
  2504. };
  2505. /**
  2506. * Gets a new Vector2(1, 1)
  2507. * @returns a new Vector2
  2508. */
  2509. Vector2.One = function () {
  2510. return new Vector2(1, 1);
  2511. };
  2512. /**
  2513. * Gets a new Vector2 set from the given index element of the given array
  2514. * @param array defines the data source
  2515. * @param offset defines the offset in the data source
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.FromArray = function (array, offset) {
  2519. if (offset === void 0) { offset = 0; }
  2520. return new Vector2(array[offset], array[offset + 1]);
  2521. };
  2522. /**
  2523. * Sets "result" from the given index element of the given array
  2524. * @param array defines the data source
  2525. * @param offset defines the offset in the data source
  2526. * @param result defines the target vector
  2527. */
  2528. Vector2.FromArrayToRef = function (array, offset, result) {
  2529. result.x = array[offset];
  2530. result.y = array[offset + 1];
  2531. };
  2532. /**
  2533. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2534. * @param value1 defines 1st point of control
  2535. * @param value2 defines 2nd point of control
  2536. * @param value3 defines 3rd point of control
  2537. * @param value4 defines 4th point of control
  2538. * @param amount defines the interpolation factor
  2539. * @returns a new Vector2
  2540. */
  2541. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * 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".
  2554. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2555. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2556. * @param value defines the value to clamp
  2557. * @param min defines the lower limit
  2558. * @param max defines the upper limit
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.Clamp = function (value, min, max) {
  2562. var x = value.x;
  2563. x = (x > max.x) ? max.x : x;
  2564. x = (x < min.x) ? min.x : x;
  2565. var y = value.y;
  2566. y = (y > max.y) ? max.y : y;
  2567. y = (y < min.y) ? min.y : y;
  2568. return new Vector2(x, y);
  2569. };
  2570. /**
  2571. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2572. * @param value1 defines the 1st control point
  2573. * @param tangent1 defines the outgoing tangent
  2574. * @param value2 defines the 2nd control point
  2575. * @param tangent2 defines the incoming tangent
  2576. * @param amount defines the interpolation factor
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2580. var squared = amount * amount;
  2581. var cubed = amount * squared;
  2582. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2583. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2584. var part3 = (cubed - (2.0 * squared)) + amount;
  2585. var part4 = cubed - squared;
  2586. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2587. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2588. return new Vector2(x, y);
  2589. };
  2590. /**
  2591. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2592. * @param start defines the start vector
  2593. * @param end defines the end vector
  2594. * @param amount defines the interpolation factor
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.Lerp = function (start, end, amount) {
  2598. var x = start.x + ((end.x - start.x) * amount);
  2599. var y = start.y + ((end.y - start.y) * amount);
  2600. return new Vector2(x, y);
  2601. };
  2602. /**
  2603. * Gets the dot product of the vector "left" and the vector "right"
  2604. * @param left defines first vector
  2605. * @param right defines second vector
  2606. * @returns the dot product (float)
  2607. */
  2608. Vector2.Dot = function (left, right) {
  2609. return left.x * right.x + left.y * right.y;
  2610. };
  2611. /**
  2612. * Returns a new Vector2 equal to the normalized given vector
  2613. * @param vector defines the vector to normalize
  2614. * @returns a new Vector2
  2615. */
  2616. Vector2.Normalize = function (vector) {
  2617. var newVector = vector.clone();
  2618. newVector.normalize();
  2619. return newVector;
  2620. };
  2621. /**
  2622. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2623. * @param left defines 1st vector
  2624. * @param right defines 2nd vector
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.Minimize = function (left, right) {
  2628. var x = (left.x < right.x) ? left.x : right.x;
  2629. var y = (left.y < right.y) ? left.y : right.y;
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2634. * @param left defines 1st vector
  2635. * @param right defines 2nd vector
  2636. * @returns a new Vector2
  2637. */
  2638. Vector2.Maximize = function (left, right) {
  2639. var x = (left.x > right.x) ? left.x : right.x;
  2640. var y = (left.y > right.y) ? left.y : right.y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2645. * @param vector defines the vector to transform
  2646. * @param transformation defines the matrix to apply
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Transform = function (vector, transformation) {
  2650. var r = Vector2.Zero();
  2651. Vector2.TransformToRef(vector, transformation, r);
  2652. return r;
  2653. };
  2654. /**
  2655. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2656. * @param vector defines the vector to transform
  2657. * @param transformation defines the matrix to apply
  2658. * @param result defines the target vector
  2659. */
  2660. Vector2.TransformToRef = function (vector, transformation, result) {
  2661. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2662. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2663. result.x = x;
  2664. result.y = y;
  2665. };
  2666. /**
  2667. * Determines if a given vector is included in a triangle
  2668. * @param p defines the vector to test
  2669. * @param p0 defines 1st triangle point
  2670. * @param p1 defines 2nd triangle point
  2671. * @param p2 defines 3rd triangle point
  2672. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2673. */
  2674. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2675. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2676. var sign = a < 0 ? -1 : 1;
  2677. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2678. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2679. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2680. };
  2681. /**
  2682. * Gets the distance between the vectors "value1" and "value2"
  2683. * @param value1 defines first vector
  2684. * @param value2 defines second vector
  2685. * @returns the distance between vectors
  2686. */
  2687. Vector2.Distance = function (value1, value2) {
  2688. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2689. };
  2690. /**
  2691. * Returns the squared distance between the vectors "value1" and "value2"
  2692. * @param value1 defines first vector
  2693. * @param value2 defines second vector
  2694. * @returns the squared distance between vectors
  2695. */
  2696. Vector2.DistanceSquared = function (value1, value2) {
  2697. var x = value1.x - value2.x;
  2698. var y = value1.y - value2.y;
  2699. return (x * x) + (y * y);
  2700. };
  2701. /**
  2702. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2703. * @param value1 defines first vector
  2704. * @param value2 defines second vector
  2705. * @returns a new Vector2
  2706. */
  2707. Vector2.Center = function (value1, value2) {
  2708. var center = value1.add(value2);
  2709. center.scaleInPlace(0.5);
  2710. return center;
  2711. };
  2712. /**
  2713. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2714. * @param p defines the middle point
  2715. * @param segA defines one point of the segment
  2716. * @param segB defines the other point of the segment
  2717. * @returns the shortest distance
  2718. */
  2719. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2720. var l2 = Vector2.DistanceSquared(segA, segB);
  2721. if (l2 === 0.0) {
  2722. return Vector2.Distance(p, segA);
  2723. }
  2724. var v = segB.subtract(segA);
  2725. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2726. var proj = segA.add(v.multiplyByFloats(t, t));
  2727. return Vector2.Distance(p, proj);
  2728. };
  2729. return Vector2;
  2730. }());
  2731. BABYLON.Vector2 = Vector2;
  2732. /**
  2733. * Classed used to store (x,y,z) vector representation
  2734. * A Vector3 is the main object used in 3D geometry
  2735. * It can represent etiher the coordinates of a point the space, either a direction
  2736. * Reminder: Babylon.js uses a left handed forward facing system
  2737. */
  2738. var Vector3 = /** @class */ (function () {
  2739. /**
  2740. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2741. * @param x defines the first coordinates (on X axis)
  2742. * @param y defines the second coordinates (on Y axis)
  2743. * @param z defines the third coordinates (on Z axis)
  2744. */
  2745. function Vector3(
  2746. /**
  2747. * Defines the first coordinates (on X axis)
  2748. */
  2749. x,
  2750. /**
  2751. * Defines the second coordinates (on Y axis)
  2752. */
  2753. y,
  2754. /**
  2755. * Defines the third coordinates (on Z axis)
  2756. */
  2757. z) {
  2758. this.x = x;
  2759. this.y = y;
  2760. this.z = z;
  2761. }
  2762. /**
  2763. * Creates a string representation of the Vector3
  2764. * @returns a string with the Vector3 coordinates.
  2765. */
  2766. Vector3.prototype.toString = function () {
  2767. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2768. };
  2769. /**
  2770. * Gets the class name
  2771. * @returns the string "Vector3"
  2772. */
  2773. Vector3.prototype.getClassName = function () {
  2774. return "Vector3";
  2775. };
  2776. /**
  2777. * Creates the Vector3 hash code
  2778. * @returns a number which tends to be unique between Vector3 instances
  2779. */
  2780. Vector3.prototype.getHashCode = function () {
  2781. var hash = this.x || 0;
  2782. hash = (hash * 397) ^ (this.y || 0);
  2783. hash = (hash * 397) ^ (this.z || 0);
  2784. return hash;
  2785. };
  2786. // Operators
  2787. /**
  2788. * Creates an array containing three elements : the coordinates of the Vector3
  2789. * @returns a new array of numbers
  2790. */
  2791. Vector3.prototype.asArray = function () {
  2792. var result = [];
  2793. this.toArray(result, 0);
  2794. return result;
  2795. };
  2796. /**
  2797. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2798. * @param array defines the destination array
  2799. * @param index defines the offset in the destination array
  2800. * @returns the current Vector3
  2801. */
  2802. Vector3.prototype.toArray = function (array, index) {
  2803. if (index === void 0) { index = 0; }
  2804. array[index] = this.x;
  2805. array[index + 1] = this.y;
  2806. array[index + 2] = this.z;
  2807. return this;
  2808. };
  2809. /**
  2810. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2811. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2812. */
  2813. Vector3.prototype.toQuaternion = function () {
  2814. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2815. };
  2816. /**
  2817. * Adds the given vector to the current Vector3
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.addInPlace = function (otherVector) {
  2822. this.x += otherVector.x;
  2823. this.y += otherVector.y;
  2824. this.z += otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the resulting Vector3
  2831. */
  2832. Vector3.prototype.add = function (otherVector) {
  2833. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2834. };
  2835. /**
  2836. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.addToRef = function (otherVector, result) {
  2842. result.x = this.x + otherVector.x;
  2843. result.y = this.y + otherVector.y;
  2844. result.z = this.z + otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Subtract the given vector from the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.subtractInPlace = function (otherVector) {
  2853. this.x -= otherVector.x;
  2854. this.y -= otherVector.y;
  2855. this.z -= otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.subtract = function (otherVector) {
  2864. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2865. };
  2866. /**
  2867. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2873. result.x = this.x - otherVector.x;
  2874. result.y = this.y - otherVector.y;
  2875. result.z = this.z - otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2880. * @param x defines the x coordinate of the operand
  2881. * @param y defines the y coordinate of the operand
  2882. * @param z defines the z coordinate of the operand
  2883. * @returns the resulting Vector3
  2884. */
  2885. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2886. return new Vector3(this.x - x, this.y - y, this.z - z);
  2887. };
  2888. /**
  2889. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2890. * @param x defines the x coordinate of the operand
  2891. * @param y defines the y coordinate of the operand
  2892. * @param z defines the z coordinate of the operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2897. result.x = this.x - x;
  2898. result.y = this.y - y;
  2899. result.z = this.z - z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2904. * @returns a new Vector3
  2905. */
  2906. Vector3.prototype.negate = function () {
  2907. return new Vector3(-this.x, -this.y, -this.z);
  2908. };
  2909. /**
  2910. * Multiplies the Vector3 coordinates by the float "scale"
  2911. * @param scale defines the multiplier factor
  2912. * @returns the current updated Vector3
  2913. */
  2914. Vector3.prototype.scaleInPlace = function (scale) {
  2915. this.x *= scale;
  2916. this.y *= scale;
  2917. this.z *= scale;
  2918. return this;
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2922. * @param scale defines the multiplier factor
  2923. * @returns a new Vector3
  2924. */
  2925. Vector3.prototype.scale = function (scale) {
  2926. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2927. };
  2928. /**
  2929. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2930. * @param scale defines the multiplier factor
  2931. * @param result defines the Vector3 object where to store the result
  2932. * @returns the current Vector3
  2933. */
  2934. Vector3.prototype.scaleToRef = function (scale, result) {
  2935. result.x = this.x * scale;
  2936. result.y = this.y * scale;
  2937. result.z = this.z * scale;
  2938. return this;
  2939. };
  2940. /**
  2941. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2942. * @param scale defines the scale factor
  2943. * @param result defines the Vector3 object where to store the result
  2944. * @returns the unmodified current Vector3
  2945. */
  2946. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2947. result.x += this.x * scale;
  2948. result.y += this.y * scale;
  2949. result.z += this.z * scale;
  2950. return this;
  2951. };
  2952. /**
  2953. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2954. * @param otherVector defines the second operand
  2955. * @returns true if both vectors are equals
  2956. */
  2957. Vector3.prototype.equals = function (otherVector) {
  2958. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2959. };
  2960. /**
  2961. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2962. * @param otherVector defines the second operand
  2963. * @param epsilon defines the minimal distance to define values as equals
  2964. * @returns true if both vectors are distant less than epsilon
  2965. */
  2966. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2967. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2968. 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);
  2969. };
  2970. /**
  2971. * Returns true if the current Vector3 coordinates equals the given floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns true if both vectors are equals
  2976. */
  2977. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2978. return this.x === x && this.y === y && this.z === z;
  2979. };
  2980. /**
  2981. * Multiplies the current Vector3 coordinates by the given ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the current updated Vector3
  2984. */
  2985. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2986. this.x *= otherVector.x;
  2987. this.y *= otherVector.y;
  2988. this.z *= otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2993. * @param otherVector defines the second operand
  2994. * @returns the new Vector3
  2995. */
  2996. Vector3.prototype.multiply = function (otherVector) {
  2997. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2998. };
  2999. /**
  3000. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3001. * @param otherVector defines the second operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3006. result.x = this.x * otherVector.x;
  3007. result.y = this.y * otherVector.y;
  3008. result.z = this.z * otherVector.z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3013. * @param x defines the x coordinate of the operand
  3014. * @param y defines the y coordinate of the operand
  3015. * @param z defines the z coordinate of the operand
  3016. * @returns the new Vector3
  3017. */
  3018. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3019. return new Vector3(this.x * x, this.y * y, this.z * z);
  3020. };
  3021. /**
  3022. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3023. * @param otherVector defines the second operand
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.divide = function (otherVector) {
  3027. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3028. };
  3029. /**
  3030. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3031. * @param otherVector defines the second operand
  3032. * @param result defines the Vector3 object where to store the result
  3033. * @returns the current Vector3
  3034. */
  3035. Vector3.prototype.divideToRef = function (otherVector, result) {
  3036. result.x = this.x / otherVector.x;
  3037. result.y = this.y / otherVector.y;
  3038. result.z = this.z / otherVector.z;
  3039. return this;
  3040. };
  3041. /**
  3042. * Divides the current Vector3 coordinates by the given ones.
  3043. * @param otherVector defines the second operand
  3044. * @returns the current updated Vector3
  3045. */
  3046. Vector3.prototype.divideInPlace = function (otherVector) {
  3047. return this.divideToRef(otherVector, this);
  3048. };
  3049. /**
  3050. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3051. * @param other defines the second operand
  3052. * @returns the current updated Vector3
  3053. */
  3054. Vector3.prototype.minimizeInPlace = function (other) {
  3055. if (other.x < this.x)
  3056. this.x = other.x;
  3057. if (other.y < this.y)
  3058. this.y = other.y;
  3059. if (other.z < this.z)
  3060. this.z = other.z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3065. * @param other defines the second operand
  3066. * @returns the current updated Vector3
  3067. */
  3068. Vector3.prototype.maximizeInPlace = function (other) {
  3069. if (other.x > this.x)
  3070. this.x = other.x;
  3071. if (other.y > this.y)
  3072. this.y = other.y;
  3073. if (other.z > this.z)
  3074. this.z = other.z;
  3075. return this;
  3076. };
  3077. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3078. /**
  3079. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3080. */
  3081. get: function () {
  3082. var absX = Math.abs(this.x);
  3083. var absY = Math.abs(this.y);
  3084. if (absX !== absY) {
  3085. return true;
  3086. }
  3087. var absZ = Math.abs(this.z);
  3088. if (absX !== absZ) {
  3089. return true;
  3090. }
  3091. if (absY !== absZ) {
  3092. return true;
  3093. }
  3094. return false;
  3095. },
  3096. enumerable: true,
  3097. configurable: true
  3098. });
  3099. // Properties
  3100. /**
  3101. * Gets the length of the Vector3
  3102. * @returns the length of the Vecto3
  3103. */
  3104. Vector3.prototype.length = function () {
  3105. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3106. };
  3107. /**
  3108. * Gets the squared length of the Vector3
  3109. * @returns squared length of the Vector3
  3110. */
  3111. Vector3.prototype.lengthSquared = function () {
  3112. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3113. };
  3114. /**
  3115. * Normalize the current Vector3.
  3116. * Please note that this is an in place operation.
  3117. * @returns the current updated Vector3
  3118. */
  3119. Vector3.prototype.normalize = function () {
  3120. var len = this.length();
  3121. if (len === 0 || len === 1.0)
  3122. return this;
  3123. var num = 1.0 / len;
  3124. this.x *= num;
  3125. this.y *= num;
  3126. this.z *= num;
  3127. return this;
  3128. };
  3129. /**
  3130. * Normalize the current Vector3 to a new vector
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.prototype.normalizeToNew = function () {
  3134. var normalized = new Vector3(0, 0, 0);
  3135. this.normalizeToRef(normalized);
  3136. return normalized;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to the reference
  3140. * @param reference define the Vector3 to update
  3141. * @returns the updated Vector3
  3142. */
  3143. Vector3.prototype.normalizeToRef = function (reference) {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0) {
  3146. reference.set(this.x, this.y, this.z);
  3147. return reference;
  3148. }
  3149. var scale = 1.0 / len;
  3150. this.scaleToRef(scale, reference);
  3151. return reference;
  3152. };
  3153. /**
  3154. * Creates a new Vector3 copied from the current Vector3
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.clone = function () {
  3158. return new Vector3(this.x, this.y, this.z);
  3159. };
  3160. /**
  3161. * Copies the given vector coordinates to the current Vector3 ones
  3162. * @param source defines the source Vector3
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.copyFrom = function (source) {
  3166. this.x = source.x;
  3167. this.y = source.y;
  3168. this.z = source.z;
  3169. return this;
  3170. };
  3171. /**
  3172. * Copies the given floats to the current Vector3 coordinates
  3173. * @param x defines the x coordinate of the operand
  3174. * @param y defines the y coordinate of the operand
  3175. * @param z defines the z coordinate of the operand
  3176. * @returns the current updated Vector3
  3177. */
  3178. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3179. this.x = x;
  3180. this.y = y;
  3181. this.z = z;
  3182. return this;
  3183. };
  3184. /**
  3185. * Copies the given floats to the current Vector3 coordinates
  3186. * @param x defines the x coordinate of the operand
  3187. * @param y defines the y coordinate of the operand
  3188. * @param z defines the z coordinate of the operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.set = function (x, y, z) {
  3192. return this.copyFromFloats(x, y, z);
  3193. };
  3194. // Statics
  3195. /**
  3196. * Get the clip factor between two vectors
  3197. * @param vector0 defines the first operand
  3198. * @param vector1 defines the second operand
  3199. * @param axis defines the axis to use
  3200. * @param size defines the size along the axis
  3201. * @returns the clip factor
  3202. */
  3203. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3204. var d0 = Vector3.Dot(vector0, axis) - size;
  3205. var d1 = Vector3.Dot(vector1, axis) - size;
  3206. var s = d0 / (d0 - d1);
  3207. return s;
  3208. };
  3209. /**
  3210. * Get angle between two vectors
  3211. * @param vector0 angle between vector0 and vector1
  3212. * @param vector1 angle between vector0 and vector1
  3213. * @param normal direction of the normal
  3214. * @return the angle between vector0 and vector1
  3215. */
  3216. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3217. var v0 = vector0.clone().normalize();
  3218. var v1 = vector1.clone().normalize();
  3219. var dot = Vector3.Dot(v0, v1);
  3220. var n = Vector3.Cross(v0, v1);
  3221. if (Vector3.Dot(n, normal) > 0) {
  3222. return Math.acos(dot);
  3223. }
  3224. return -Math.acos(dot);
  3225. };
  3226. /**
  3227. * Returns a new Vector3 set from the index "offset" of the given array
  3228. * @param array defines the source array
  3229. * @param offset defines the offset in the source array
  3230. * @returns the new Vector3
  3231. */
  3232. Vector3.FromArray = function (array, offset) {
  3233. if (!offset) {
  3234. offset = 0;
  3235. }
  3236. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3237. };
  3238. /**
  3239. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3240. * This function is deprecated. Use FromArray instead
  3241. * @param array defines the source array
  3242. * @param offset defines the offset in the source array
  3243. * @returns the new Vector3
  3244. */
  3245. Vector3.FromFloatArray = function (array, offset) {
  3246. return Vector3.FromArray(array, offset);
  3247. };
  3248. /**
  3249. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @param result defines the Vector3 where to store the result
  3253. */
  3254. Vector3.FromArrayToRef = function (array, offset, result) {
  3255. result.x = array[offset];
  3256. result.y = array[offset + 1];
  3257. result.z = array[offset + 2];
  3258. };
  3259. /**
  3260. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3261. * This function is deprecated. Use FromArrayToRef instead.
  3262. * @param array defines the source array
  3263. * @param offset defines the offset in the source array
  3264. * @param result defines the Vector3 where to store the result
  3265. */
  3266. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3267. return Vector3.FromArrayToRef(array, offset, result);
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the given floats.
  3271. * @param x defines the x coordinate of the source
  3272. * @param y defines the y coordinate of the source
  3273. * @param z defines the z coordinate of the source
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3277. result.x = x;
  3278. result.y = y;
  3279. result.z = z;
  3280. };
  3281. /**
  3282. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3283. * @returns a new empty Vector3
  3284. */
  3285. Vector3.Zero = function () {
  3286. return new Vector3(0.0, 0.0, 0.0);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3290. * @returns a new unit Vector3
  3291. */
  3292. Vector3.One = function () {
  3293. return new Vector3(1.0, 1.0, 1.0);
  3294. };
  3295. /**
  3296. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3297. * @returns a new up Vector3
  3298. */
  3299. Vector3.Up = function () {
  3300. return new Vector3(0.0, 1.0, 0.0);
  3301. };
  3302. /**
  3303. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3304. * @returns a new forward Vector3
  3305. */
  3306. Vector3.Forward = function () {
  3307. return new Vector3(0.0, 0.0, 1.0);
  3308. };
  3309. /**
  3310. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3311. * @returns a new right Vector3
  3312. */
  3313. Vector3.Right = function () {
  3314. return new Vector3(1.0, 0.0, 0.0);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3318. * @returns a new left Vector3
  3319. */
  3320. Vector3.Left = function () {
  3321. return new Vector3(-1.0, 0.0, 0.0);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3325. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3326. * @param vector defines the Vector3 to transform
  3327. * @param transformation defines the transformation matrix
  3328. * @returns the transformed Vector3
  3329. */
  3330. Vector3.TransformCoordinates = function (vector, transformation) {
  3331. var result = Vector3.Zero();
  3332. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3337. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3338. * @param vector defines the Vector3 to transform
  3339. * @param transformation defines the transformation matrix
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3343. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3344. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3345. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3346. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3347. result.x = x / w;
  3348. result.y = y / w;
  3349. result.z = z / w;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3353. * This method computes tranformed coordinates only, not transformed direction vectors
  3354. * @param x define the x coordinate of the source vector
  3355. * @param y define the y coordinate of the source vector
  3356. * @param z define the z coordinate of the source vector
  3357. * @param transformation defines the transformation matrix
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3361. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3362. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3363. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3364. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3365. result.x = rx / rw;
  3366. result.y = ry / rw;
  3367. result.z = rz / rw;
  3368. };
  3369. /**
  3370. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3371. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3372. * @param vector defines the Vector3 to transform
  3373. * @param transformation defines the transformation matrix
  3374. * @returns the new Vector3
  3375. */
  3376. Vector3.TransformNormal = function (vector, transformation) {
  3377. var result = Vector3.Zero();
  3378. Vector3.TransformNormalToRef(vector, transformation, result);
  3379. return result;
  3380. };
  3381. /**
  3382. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3383. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3384. * @param vector defines the Vector3 to transform
  3385. * @param transformation defines the transformation matrix
  3386. * @param result defines the Vector3 where to store the result
  3387. */
  3388. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3389. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3390. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3391. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3392. result.x = x;
  3393. result.y = y;
  3394. result.z = z;
  3395. };
  3396. /**
  3397. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param x define the x coordinate of the source vector
  3400. * @param y define the y coordinate of the source vector
  3401. * @param z define the z coordinate of the source vector
  3402. * @param transformation defines the transformation matrix
  3403. * @param result defines the Vector3 where to store the result
  3404. */
  3405. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3406. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3407. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3408. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3409. };
  3410. /**
  3411. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3412. * @param value1 defines the first control point
  3413. * @param value2 defines the second control point
  3414. * @param value3 defines the third control point
  3415. * @param value4 defines the fourth control point
  3416. * @param amount defines the amount on the spline to use
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3420. var squared = amount * amount;
  3421. var cubed = amount * squared;
  3422. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3423. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3424. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3425. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3426. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3427. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3428. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3429. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3430. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3431. return new Vector3(x, y, z);
  3432. };
  3433. /**
  3434. * 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"
  3435. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3436. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3437. * @param value defines the current value
  3438. * @param min defines the lower range value
  3439. * @param max defines the upper range value
  3440. * @returns the new Vector3
  3441. */
  3442. Vector3.Clamp = function (value, min, max) {
  3443. var x = value.x;
  3444. x = (x > max.x) ? max.x : x;
  3445. x = (x < min.x) ? min.x : x;
  3446. var y = value.y;
  3447. y = (y > max.y) ? max.y : y;
  3448. y = (y < min.y) ? min.y : y;
  3449. var z = value.z;
  3450. z = (z > max.z) ? max.z : z;
  3451. z = (z < min.z) ? min.z : z;
  3452. return new Vector3(x, y, z);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3456. * @param value1 defines the first control point
  3457. * @param tangent1 defines the first tangent vector
  3458. * @param value2 defines the second control point
  3459. * @param tangent2 defines the second tangent vector
  3460. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3461. * @returns the new Vector3
  3462. */
  3463. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3464. var squared = amount * amount;
  3465. var cubed = amount * squared;
  3466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3468. var part3 = (cubed - (2.0 * squared)) + amount;
  3469. var part4 = cubed - squared;
  3470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3472. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3473. return new Vector3(x, y, z);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3477. * @param start defines the start value
  3478. * @param end defines the end value
  3479. * @param amount max defines amount between both (between 0 and 1)
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.Lerp = function (start, end, amount) {
  3483. var result = new Vector3(0, 0, 0);
  3484. Vector3.LerpToRef(start, end, amount, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3489. * @param start defines the start value
  3490. * @param end defines the end value
  3491. * @param amount max defines amount between both (between 0 and 1)
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.LerpToRef = function (start, end, amount, result) {
  3495. result.x = start.x + ((end.x - start.x) * amount);
  3496. result.y = start.y + ((end.y - start.y) * amount);
  3497. result.z = start.z + ((end.z - start.z) * amount);
  3498. };
  3499. /**
  3500. * Returns the dot product (float) between the vectors "left" and "right"
  3501. * @param left defines the left operand
  3502. * @param right defines the right operand
  3503. * @returns the dot product
  3504. */
  3505. Vector3.Dot = function (left, right) {
  3506. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3507. };
  3508. /**
  3509. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3510. * The cross product is then orthogonal to both "left" and "right"
  3511. * @param left defines the left operand
  3512. * @param right defines the right operand
  3513. * @returns the cross product
  3514. */
  3515. Vector3.Cross = function (left, right) {
  3516. var result = Vector3.Zero();
  3517. Vector3.CrossToRef(left, right, result);
  3518. return result;
  3519. };
  3520. /**
  3521. * Sets the given vector "result" with the cross product of "left" and "right"
  3522. * The cross product is then orthogonal to both "left" and "right"
  3523. * @param left defines the left operand
  3524. * @param right defines the right operand
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.CrossToRef = function (left, right, result) {
  3528. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3529. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3530. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3531. result.copyFrom(MathTmp.Vector3[0]);
  3532. };
  3533. /**
  3534. * Returns a new Vector3 as the normalization of the given vector
  3535. * @param vector defines the Vector3 to normalize
  3536. * @returns the new Vector3
  3537. */
  3538. Vector3.Normalize = function (vector) {
  3539. var result = Vector3.Zero();
  3540. Vector3.NormalizeToRef(vector, result);
  3541. return result;
  3542. };
  3543. /**
  3544. * Sets the given vector "result" with the normalization of the given first vector
  3545. * @param vector defines the Vector3 to normalize
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.NormalizeToRef = function (vector, result) {
  3549. result.copyFrom(vector);
  3550. result.normalize();
  3551. };
  3552. /**
  3553. * Project a Vector3 onto screen space
  3554. * @param vector defines the Vector3 to project
  3555. * @param world defines the world matrix to use
  3556. * @param transform defines the transform (view x projection) matrix to use
  3557. * @param viewport defines the screen viewport to use
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Project = function (vector, world, transform, viewport) {
  3561. var cw = viewport.width;
  3562. var ch = viewport.height;
  3563. var cx = viewport.x;
  3564. var cy = viewport.y;
  3565. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3566. 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);
  3567. var matrix = MathTmp.Matrix[0];
  3568. world.multiplyToRef(transform, matrix);
  3569. matrix.multiplyToRef(viewportMatrix, matrix);
  3570. return Vector3.TransformCoordinates(vector, matrix);
  3571. };
  3572. /**
  3573. * Unproject from screen space to object space
  3574. * @param source defines the screen space Vector3 to use
  3575. * @param viewportWidth defines the current width of the viewport
  3576. * @param viewportHeight defines the current height of the viewport
  3577. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3578. * @param transform defines the transform (view x projection) matrix to use
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3582. var matrix = MathTmp.Matrix[0];
  3583. world.multiplyToRef(transform, matrix);
  3584. matrix.invert();
  3585. source.x = source.x / viewportWidth * 2 - 1;
  3586. source.y = -(source.y / viewportHeight * 2 - 1);
  3587. var vector = Vector3.TransformCoordinates(source, matrix);
  3588. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3589. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3590. vector = vector.scale(1.0 / num);
  3591. }
  3592. return vector;
  3593. };
  3594. /**
  3595. * Unproject from screen space to object space
  3596. * @param source defines the screen space Vector3 to use
  3597. * @param viewportWidth defines the current width of the viewport
  3598. * @param viewportHeight defines the current height of the viewport
  3599. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3600. * @param view defines the view matrix to use
  3601. * @param projection defines the projection matrix to use
  3602. * @returns the new Vector3
  3603. */
  3604. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3605. var result = Vector3.Zero();
  3606. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3607. return result;
  3608. };
  3609. /**
  3610. * Unproject from screen space to object space
  3611. * @param source defines the screen space Vector3 to use
  3612. * @param viewportWidth defines the current width of the viewport
  3613. * @param viewportHeight defines the current height of the viewport
  3614. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3615. * @param view defines the view matrix to use
  3616. * @param projection defines the projection matrix to use
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3620. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3621. };
  3622. /**
  3623. * Unproject from screen space to object space
  3624. * @param sourceX defines the screen space x coordinate to use
  3625. * @param sourceY defines the screen space y coordinate to use
  3626. * @param sourceZ defines the screen space z coordinate to use
  3627. * @param viewportWidth defines the current width of the viewport
  3628. * @param viewportHeight defines the current height of the viewport
  3629. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3630. * @param view defines the view matrix to use
  3631. * @param projection defines the projection matrix to use
  3632. * @param result defines the Vector3 where to store the result
  3633. */
  3634. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3635. var matrix = MathTmp.Matrix[0];
  3636. world.multiplyToRef(view, matrix);
  3637. matrix.multiplyToRef(projection, matrix);
  3638. matrix.invert();
  3639. var screenSource = MathTmp.Vector3[0];
  3640. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3641. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3642. screenSource.z = 2 * sourceZ - 1.0;
  3643. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3644. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3645. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3646. result.scaleInPlace(1.0 / num);
  3647. }
  3648. };
  3649. /**
  3650. * Gets the minimal coordinate values between two Vector3
  3651. * @param left defines the first operand
  3652. * @param right defines the second operand
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Minimize = function (left, right) {
  3656. var min = left.clone();
  3657. min.minimizeInPlace(right);
  3658. return min;
  3659. };
  3660. /**
  3661. * Gets the maximal coordinate values between two Vector3
  3662. * @param left defines the first operand
  3663. * @param right defines the second operand
  3664. * @returns the new Vector3
  3665. */
  3666. Vector3.Maximize = function (left, right) {
  3667. var max = left.clone();
  3668. max.maximizeInPlace(right);
  3669. return max;
  3670. };
  3671. /**
  3672. * Returns the distance between the vectors "value1" and "value2"
  3673. * @param value1 defines the first operand
  3674. * @param value2 defines the second operand
  3675. * @returns the distance
  3676. */
  3677. Vector3.Distance = function (value1, value2) {
  3678. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3679. };
  3680. /**
  3681. * Returns the squared distance between the vectors "value1" and "value2"
  3682. * @param value1 defines the first operand
  3683. * @param value2 defines the second operand
  3684. * @returns the squared distance
  3685. */
  3686. Vector3.DistanceSquared = function (value1, value2) {
  3687. var x = value1.x - value2.x;
  3688. var y = value1.y - value2.y;
  3689. var z = value1.z - value2.z;
  3690. return (x * x) + (y * y) + (z * z);
  3691. };
  3692. /**
  3693. * Returns a new Vector3 located at the center between "value1" and "value2"
  3694. * @param value1 defines the first operand
  3695. * @param value2 defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Center = function (value1, value2) {
  3699. var center = value1.add(value2);
  3700. center.scaleInPlace(0.5);
  3701. return center;
  3702. };
  3703. /**
  3704. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3705. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3706. * to something in order to rotate it from its local system to the given target system
  3707. * Note: axis1, axis2 and axis3 are normalized during this operation
  3708. * @param axis1 defines the first axis
  3709. * @param axis2 defines the second axis
  3710. * @param axis3 defines the third axis
  3711. * @returns a new Vector3
  3712. */
  3713. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3714. var rotation = Vector3.Zero();
  3715. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3716. return rotation;
  3717. };
  3718. /**
  3719. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3720. * @param axis1 defines the first axis
  3721. * @param axis2 defines the second axis
  3722. * @param axis3 defines the third axis
  3723. * @param ref defines the Vector3 where to store the result
  3724. */
  3725. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3726. var quat = MathTmp.Quaternion[0];
  3727. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3728. quat.toEulerAnglesToRef(ref);
  3729. };
  3730. return Vector3;
  3731. }());
  3732. BABYLON.Vector3 = Vector3;
  3733. //Vector4 class created for EulerAngle class conversion to Quaternion
  3734. var Vector4 = /** @class */ (function () {
  3735. /**
  3736. * Creates a Vector4 object from the given floats.
  3737. */
  3738. function Vector4(x, y, z, w) {
  3739. this.x = x;
  3740. this.y = y;
  3741. this.z = z;
  3742. this.w = w;
  3743. }
  3744. /**
  3745. * Returns the string with the Vector4 coordinates.
  3746. */
  3747. Vector4.prototype.toString = function () {
  3748. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3749. };
  3750. /**
  3751. * Returns the string "Vector4".
  3752. */
  3753. Vector4.prototype.getClassName = function () {
  3754. return "Vector4";
  3755. };
  3756. /**
  3757. * Returns the Vector4 hash code.
  3758. */
  3759. Vector4.prototype.getHashCode = function () {
  3760. var hash = this.x || 0;
  3761. hash = (hash * 397) ^ (this.y || 0);
  3762. hash = (hash * 397) ^ (this.z || 0);
  3763. hash = (hash * 397) ^ (this.w || 0);
  3764. return hash;
  3765. };
  3766. // Operators
  3767. /**
  3768. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.asArray = function () {
  3771. var result = new Array();
  3772. this.toArray(result, 0);
  3773. return result;
  3774. };
  3775. /**
  3776. * Populates the given array from the given index with the Vector4 coordinates.
  3777. * Returns the Vector4.
  3778. */
  3779. Vector4.prototype.toArray = function (array, index) {
  3780. if (index === undefined) {
  3781. index = 0;
  3782. }
  3783. array[index] = this.x;
  3784. array[index + 1] = this.y;
  3785. array[index + 2] = this.z;
  3786. array[index + 3] = this.w;
  3787. return this;
  3788. };
  3789. /**
  3790. * Adds the given vector to the current Vector4.
  3791. * Returns the updated Vector4.
  3792. */
  3793. Vector4.prototype.addInPlace = function (otherVector) {
  3794. this.x += otherVector.x;
  3795. this.y += otherVector.y;
  3796. this.z += otherVector.z;
  3797. this.w += otherVector.w;
  3798. return this;
  3799. };
  3800. /**
  3801. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3802. */
  3803. Vector4.prototype.add = function (otherVector) {
  3804. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3805. };
  3806. /**
  3807. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3808. * Returns the current Vector4.
  3809. */
  3810. Vector4.prototype.addToRef = function (otherVector, result) {
  3811. result.x = this.x + otherVector.x;
  3812. result.y = this.y + otherVector.y;
  3813. result.z = this.z + otherVector.z;
  3814. result.w = this.w + otherVector.w;
  3815. return this;
  3816. };
  3817. /**
  3818. * Subtract in place the given vector from the current Vector4.
  3819. * Returns the updated Vector4.
  3820. */
  3821. Vector4.prototype.subtractInPlace = function (otherVector) {
  3822. this.x -= otherVector.x;
  3823. this.y -= otherVector.y;
  3824. this.z -= otherVector.z;
  3825. this.w -= otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3830. */
  3831. Vector4.prototype.subtract = function (otherVector) {
  3832. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3833. };
  3834. /**
  3835. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3836. * Returns the current Vector4.
  3837. */
  3838. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3839. result.x = this.x - otherVector.x;
  3840. result.y = this.y - otherVector.y;
  3841. result.z = this.z - otherVector.z;
  3842. result.w = this.w - otherVector.w;
  3843. return this;
  3844. };
  3845. /**
  3846. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3847. */
  3848. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3849. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3850. };
  3851. /**
  3852. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3853. * Returns the current Vector4.
  3854. */
  3855. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3856. result.x = this.x - x;
  3857. result.y = this.y - y;
  3858. result.z = this.z - z;
  3859. result.w = this.w - w;
  3860. return this;
  3861. };
  3862. /**
  3863. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3864. */
  3865. Vector4.prototype.negate = function () {
  3866. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3867. };
  3868. /**
  3869. * Multiplies the current Vector4 coordinates by scale (float).
  3870. * Returns the updated Vector4.
  3871. */
  3872. Vector4.prototype.scaleInPlace = function (scale) {
  3873. this.x *= scale;
  3874. this.y *= scale;
  3875. this.z *= scale;
  3876. this.w *= scale;
  3877. return this;
  3878. };
  3879. /**
  3880. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3881. */
  3882. Vector4.prototype.scale = function (scale) {
  3883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3884. };
  3885. /**
  3886. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3887. * Returns the current Vector4.
  3888. */
  3889. Vector4.prototype.scaleToRef = function (scale, result) {
  3890. result.x = this.x * scale;
  3891. result.y = this.y * scale;
  3892. result.z = this.z * scale;
  3893. result.w = this.w * scale;
  3894. return this;
  3895. };
  3896. /**
  3897. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3898. * @param scale defines the scale factor
  3899. * @param result defines the Vector4 object where to store the result
  3900. * @returns the unmodified current Vector4
  3901. */
  3902. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3903. result.x += this.x * scale;
  3904. result.y += this.y * scale;
  3905. result.z += this.z * scale;
  3906. result.w += this.w * scale;
  3907. return this;
  3908. };
  3909. /**
  3910. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3911. */
  3912. Vector4.prototype.equals = function (otherVector) {
  3913. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3914. };
  3915. /**
  3916. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3917. */
  3918. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3919. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3920. return otherVector
  3921. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3922. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3923. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3925. };
  3926. /**
  3927. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3928. */
  3929. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3930. return this.x === x && this.y === y && this.z === z && this.w === w;
  3931. };
  3932. /**
  3933. * Multiplies in place the current Vector4 by the given one.
  3934. * Returns the updated Vector4.
  3935. */
  3936. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3937. this.x *= otherVector.x;
  3938. this.y *= otherVector.y;
  3939. this.z *= otherVector.z;
  3940. this.w *= otherVector.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3945. */
  3946. Vector4.prototype.multiply = function (otherVector) {
  3947. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3948. };
  3949. /**
  3950. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3951. * Returns the current Vector4.
  3952. */
  3953. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3954. result.x = this.x * otherVector.x;
  3955. result.y = this.y * otherVector.y;
  3956. result.z = this.z * otherVector.z;
  3957. result.w = this.w * otherVector.w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3962. */
  3963. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3964. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3965. };
  3966. /**
  3967. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3968. */
  3969. Vector4.prototype.divide = function (otherVector) {
  3970. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3971. };
  3972. /**
  3973. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3974. * Returns the current Vector4.
  3975. */
  3976. Vector4.prototype.divideToRef = function (otherVector, result) {
  3977. result.x = this.x / otherVector.x;
  3978. result.y = this.y / otherVector.y;
  3979. result.z = this.z / otherVector.z;
  3980. result.w = this.w / otherVector.w;
  3981. return this;
  3982. };
  3983. /**
  3984. * Divides the current Vector3 coordinates by the given ones.
  3985. * @returns the updated Vector3.
  3986. */
  3987. Vector4.prototype.divideInPlace = function (otherVector) {
  3988. return this.divideToRef(otherVector, this);
  3989. };
  3990. /**
  3991. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3992. * @param other defines the second operand
  3993. * @returns the current updated Vector4
  3994. */
  3995. Vector4.prototype.minimizeInPlace = function (other) {
  3996. if (other.x < this.x)
  3997. this.x = other.x;
  3998. if (other.y < this.y)
  3999. this.y = other.y;
  4000. if (other.z < this.z)
  4001. this.z = other.z;
  4002. if (other.w < this.w)
  4003. this.w = other.w;
  4004. return this;
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the maximum 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.maximizeInPlace = 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. // Properties
  4023. /**
  4024. * Returns the Vector4 length (float).
  4025. */
  4026. Vector4.prototype.length = function () {
  4027. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4028. };
  4029. /**
  4030. * Returns the Vector4 squared length (float).
  4031. */
  4032. Vector4.prototype.lengthSquared = function () {
  4033. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4034. };
  4035. // Methods
  4036. /**
  4037. * Normalizes in place the Vector4.
  4038. * Returns the updated Vector4.
  4039. */
  4040. Vector4.prototype.normalize = function () {
  4041. var len = this.length();
  4042. if (len === 0)
  4043. return this;
  4044. var num = 1.0 / len;
  4045. this.x *= num;
  4046. this.y *= num;
  4047. this.z *= num;
  4048. this.w *= num;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4053. */
  4054. Vector4.prototype.toVector3 = function () {
  4055. return new Vector3(this.x, this.y, this.z);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 copied from the current one.
  4059. */
  4060. Vector4.prototype.clone = function () {
  4061. return new Vector4(this.x, this.y, this.z, this.w);
  4062. };
  4063. /**
  4064. * Updates the current Vector4 with the given one coordinates.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.copyFrom = function (source) {
  4068. this.x = source.x;
  4069. this.y = source.y;
  4070. this.z = source.z;
  4071. this.w = source.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Updates the current Vector4 coordinates with the given floats.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4079. this.x = x;
  4080. this.y = y;
  4081. this.z = z;
  4082. this.w = w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Updates the current Vector4 coordinates with the given floats.
  4087. * Returns the updated Vector4.
  4088. */
  4089. Vector4.prototype.set = function (x, y, z, w) {
  4090. return this.copyFromFloats(x, y, z, w);
  4091. };
  4092. // Statics
  4093. /**
  4094. * Returns a new Vector4 set from the starting index of the given array.
  4095. */
  4096. Vector4.FromArray = function (array, offset) {
  4097. if (!offset) {
  4098. offset = 0;
  4099. }
  4100. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4101. };
  4102. /**
  4103. * Updates the given vector "result" from the starting index of the given array.
  4104. */
  4105. Vector4.FromArrayToRef = function (array, offset, result) {
  4106. result.x = array[offset];
  4107. result.y = array[offset + 1];
  4108. result.z = array[offset + 2];
  4109. result.w = array[offset + 3];
  4110. };
  4111. /**
  4112. * Updates the given vector "result" from the starting index of the given Float32Array.
  4113. */
  4114. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4115. Vector4.FromArrayToRef(array, offset, result);
  4116. };
  4117. /**
  4118. * Updates the given vector "result" coordinates from the given floats.
  4119. */
  4120. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4121. result.x = x;
  4122. result.y = y;
  4123. result.z = z;
  4124. result.w = w;
  4125. };
  4126. /**
  4127. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4128. */
  4129. Vector4.Zero = function () {
  4130. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4134. */
  4135. Vector4.One = function () {
  4136. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4137. };
  4138. /**
  4139. * Returns a new normalized Vector4 from the given one.
  4140. */
  4141. Vector4.Normalize = function (vector) {
  4142. var result = Vector4.Zero();
  4143. Vector4.NormalizeToRef(vector, result);
  4144. return result;
  4145. };
  4146. /**
  4147. * Updates the given vector "result" from the normalization of the given one.
  4148. */
  4149. Vector4.NormalizeToRef = function (vector, result) {
  4150. result.copyFrom(vector);
  4151. result.normalize();
  4152. };
  4153. Vector4.Minimize = function (left, right) {
  4154. var min = left.clone();
  4155. min.minimizeInPlace(right);
  4156. return min;
  4157. };
  4158. Vector4.Maximize = function (left, right) {
  4159. var max = left.clone();
  4160. max.maximizeInPlace(right);
  4161. return max;
  4162. };
  4163. /**
  4164. * Returns the distance (float) between the vectors "value1" and "value2".
  4165. */
  4166. Vector4.Distance = function (value1, value2) {
  4167. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4168. };
  4169. /**
  4170. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4171. */
  4172. Vector4.DistanceSquared = function (value1, value2) {
  4173. var x = value1.x - value2.x;
  4174. var y = value1.y - value2.y;
  4175. var z = value1.z - value2.z;
  4176. var w = value1.w - value2.w;
  4177. return (x * x) + (y * y) + (z * z) + (w * w);
  4178. };
  4179. /**
  4180. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Center = function (value1, value2) {
  4183. var center = value1.add(value2);
  4184. center.scaleInPlace(0.5);
  4185. return center;
  4186. };
  4187. /**
  4188. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4189. * This methods computes transformed normalized direction vectors only.
  4190. */
  4191. Vector4.TransformNormal = function (vector, transformation) {
  4192. var result = Vector4.Zero();
  4193. Vector4.TransformNormalToRef(vector, transformation, result);
  4194. return result;
  4195. };
  4196. /**
  4197. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4198. * This methods computes transformed normalized direction vectors only.
  4199. */
  4200. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4201. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4202. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4203. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4204. result.x = x;
  4205. result.y = y;
  4206. result.z = z;
  4207. result.w = vector.w;
  4208. };
  4209. /**
  4210. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4211. * This methods computes transformed normalized direction vectors only.
  4212. */
  4213. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4214. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4215. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4216. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4217. result.w = w;
  4218. };
  4219. return Vector4;
  4220. }());
  4221. BABYLON.Vector4 = Vector4;
  4222. var Size = /** @class */ (function () {
  4223. /**
  4224. * Creates a Size object from the given width and height (floats).
  4225. */
  4226. function Size(width, height) {
  4227. this.width = width;
  4228. this.height = height;
  4229. }
  4230. // Returns a string with the Size width and height.
  4231. Size.prototype.toString = function () {
  4232. return "{W: " + this.width + ", H: " + this.height + "}";
  4233. };
  4234. /**
  4235. * Returns the string "Size"
  4236. */
  4237. Size.prototype.getClassName = function () {
  4238. return "Size";
  4239. };
  4240. /**
  4241. * Returns the Size hash code.
  4242. */
  4243. Size.prototype.getHashCode = function () {
  4244. var hash = this.width || 0;
  4245. hash = (hash * 397) ^ (this.height || 0);
  4246. return hash;
  4247. };
  4248. /**
  4249. * Updates the current size from the given one.
  4250. * Returns the updated Size.
  4251. */
  4252. Size.prototype.copyFrom = function (src) {
  4253. this.width = src.width;
  4254. this.height = src.height;
  4255. };
  4256. /**
  4257. * Updates in place the current Size from the given floats.
  4258. * Returns the updated Size.
  4259. */
  4260. Size.prototype.copyFromFloats = function (width, height) {
  4261. this.width = width;
  4262. this.height = height;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates in place the current Size from the given floats.
  4267. * Returns the updated Size.
  4268. */
  4269. Size.prototype.set = function (width, height) {
  4270. return this.copyFromFloats(width, height);
  4271. };
  4272. /**
  4273. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4274. */
  4275. Size.prototype.multiplyByFloats = function (w, h) {
  4276. return new Size(this.width * w, this.height * h);
  4277. };
  4278. /**
  4279. * Returns a new Size copied from the given one.
  4280. */
  4281. Size.prototype.clone = function () {
  4282. return new Size(this.width, this.height);
  4283. };
  4284. /**
  4285. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4286. */
  4287. Size.prototype.equals = function (other) {
  4288. if (!other) {
  4289. return false;
  4290. }
  4291. return (this.width === other.width) && (this.height === other.height);
  4292. };
  4293. Object.defineProperty(Size.prototype, "surface", {
  4294. /**
  4295. * Returns the surface of the Size : width * height (float).
  4296. */
  4297. get: function () {
  4298. return this.width * this.height;
  4299. },
  4300. enumerable: true,
  4301. configurable: true
  4302. });
  4303. /**
  4304. * Returns a new Size set to (0.0, 0.0)
  4305. */
  4306. Size.Zero = function () {
  4307. return new Size(0.0, 0.0);
  4308. };
  4309. /**
  4310. * Returns a new Size set as the addition result of the current Size and the given one.
  4311. */
  4312. Size.prototype.add = function (otherSize) {
  4313. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4314. return r;
  4315. };
  4316. /**
  4317. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4318. */
  4319. Size.prototype.subtract = function (otherSize) {
  4320. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4321. return r;
  4322. };
  4323. /**
  4324. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4325. */
  4326. Size.Lerp = function (start, end, amount) {
  4327. var w = start.width + ((end.width - start.width) * amount);
  4328. var h = start.height + ((end.height - start.height) * amount);
  4329. return new Size(w, h);
  4330. };
  4331. return Size;
  4332. }());
  4333. BABYLON.Size = Size;
  4334. /**
  4335. * Class used to store quaternion data
  4336. * @see https://en.wikipedia.org/wiki/Quaternion
  4337. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4338. */
  4339. var Quaternion = /** @class */ (function () {
  4340. /**
  4341. * Creates a new Quaternion from the given floats
  4342. * @param x defines the first component (0 by default)
  4343. * @param y defines the second component (0 by default)
  4344. * @param z defines the third component (0 by default)
  4345. * @param w defines the fourth component (1.0 by default)
  4346. */
  4347. function Quaternion(
  4348. /** defines the first component (0 by default) */
  4349. x,
  4350. /** defines the second component (0 by default) */
  4351. y,
  4352. /** defines the third component (0 by default) */
  4353. z,
  4354. /** defines the fourth component (1.0 by default) */
  4355. w) {
  4356. if (x === void 0) { x = 0.0; }
  4357. if (y === void 0) { y = 0.0; }
  4358. if (z === void 0) { z = 0.0; }
  4359. if (w === void 0) { w = 1.0; }
  4360. this.x = x;
  4361. this.y = y;
  4362. this.z = z;
  4363. this.w = w;
  4364. }
  4365. /**
  4366. * Gets a string representation for the current quaternion
  4367. * @returns a string with the Quaternion coordinates
  4368. */
  4369. Quaternion.prototype.toString = function () {
  4370. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4371. };
  4372. /**
  4373. * Gets the class name of the quaternion
  4374. * @returns the string "Quaternion"
  4375. */
  4376. Quaternion.prototype.getClassName = function () {
  4377. return "Quaternion";
  4378. };
  4379. /**
  4380. * Gets a hash code for this quaternion
  4381. * @returns the quaternion hash code
  4382. */
  4383. Quaternion.prototype.getHashCode = function () {
  4384. var hash = this.x || 0;
  4385. hash = (hash * 397) ^ (this.y || 0);
  4386. hash = (hash * 397) ^ (this.z || 0);
  4387. hash = (hash * 397) ^ (this.w || 0);
  4388. return hash;
  4389. };
  4390. /**
  4391. * Copy the quaternion to an array
  4392. * @returns a new array populated with 4 elements from the quaternion coordinates
  4393. */
  4394. Quaternion.prototype.asArray = function () {
  4395. return [this.x, this.y, this.z, this.w];
  4396. };
  4397. /**
  4398. * Check if two quaternions are equals
  4399. * @param otherQuaternion defines the second operand
  4400. * @return true if the current quaternion and the given one coordinates are strictly equals
  4401. */
  4402. Quaternion.prototype.equals = function (otherQuaternion) {
  4403. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4404. };
  4405. /**
  4406. * Clone the current quaternion
  4407. * @returns a new quaternion copied from the current one
  4408. */
  4409. Quaternion.prototype.clone = function () {
  4410. return new Quaternion(this.x, this.y, this.z, this.w);
  4411. };
  4412. /**
  4413. * Copy a quaternion to the current one
  4414. * @param other defines the other quaternion
  4415. * @returns the updated current quaternion
  4416. */
  4417. Quaternion.prototype.copyFrom = function (other) {
  4418. this.x = other.x;
  4419. this.y = other.y;
  4420. this.z = other.z;
  4421. this.w = other.w;
  4422. return this;
  4423. };
  4424. /**
  4425. * Updates the current quaternion with the given float coordinates
  4426. * @param x defines the x coordinate
  4427. * @param y defines the y coordinate
  4428. * @param z defines the z coordinate
  4429. * @param w defines the w coordinate
  4430. * @returns the updated current quaternion
  4431. */
  4432. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4433. this.x = x;
  4434. this.y = y;
  4435. this.z = z;
  4436. this.w = w;
  4437. return this;
  4438. };
  4439. /**
  4440. * Updates the current quaternion from the given float coordinates
  4441. * @param x defines the x coordinate
  4442. * @param y defines the y coordinate
  4443. * @param z defines the z coordinate
  4444. * @param w defines the w coordinate
  4445. * @returns the updated current quaternion
  4446. */
  4447. Quaternion.prototype.set = function (x, y, z, w) {
  4448. return this.copyFromFloats(x, y, z, w);
  4449. };
  4450. /**
  4451. * Adds two quaternions
  4452. * @param other defines the second operand
  4453. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4454. */
  4455. Quaternion.prototype.add = function (other) {
  4456. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4457. };
  4458. /**
  4459. * Add a quaternion to the current one
  4460. * @param other defines the quaternion to add
  4461. * @returns the current quaternion
  4462. */
  4463. Quaternion.prototype.addInPlace = function (other) {
  4464. this.x += other.x;
  4465. this.y += other.y;
  4466. this.z += other.z;
  4467. this.w += other.w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Subtract two quaternions
  4472. * @param other defines the second operand
  4473. * @returns a new quaternion as the subtraction result of the given one from the current one
  4474. */
  4475. Quaternion.prototype.subtract = function (other) {
  4476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4477. };
  4478. /**
  4479. * Multiplies the current quaternion by a scale factor
  4480. * @param value defines the scale factor
  4481. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4482. */
  4483. Quaternion.prototype.scale = function (value) {
  4484. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4485. };
  4486. /**
  4487. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4488. * @param scale defines the scale factor
  4489. * @param result defines the Quaternion object where to store the result
  4490. * @returns the unmodified current quaternion
  4491. */
  4492. Quaternion.prototype.scaleToRef = function (scale, result) {
  4493. result.x = this.x * scale;
  4494. result.y = this.y * scale;
  4495. result.z = this.z * scale;
  4496. result.w = this.w * scale;
  4497. return this;
  4498. };
  4499. /**
  4500. * Multiplies in place the current quaternion by a scale factor
  4501. * @param value defines the scale factor
  4502. * @returns the current modified quaternion
  4503. */
  4504. Quaternion.prototype.scaleInPlace = function (value) {
  4505. this.x *= value;
  4506. this.y *= value;
  4507. this.z *= value;
  4508. this.w *= value;
  4509. return this;
  4510. };
  4511. /**
  4512. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4513. * @param scale defines the scale factor
  4514. * @param result defines the Quaternion object where to store the result
  4515. * @returns the unmodified current quaternion
  4516. */
  4517. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4518. result.x += this.x * scale;
  4519. result.y += this.y * scale;
  4520. result.z += this.z * scale;
  4521. result.w += this.w * scale;
  4522. return this;
  4523. };
  4524. /**
  4525. * Multiplies two quaternions
  4526. * @param q1 defines the second operand
  4527. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4528. */
  4529. Quaternion.prototype.multiply = function (q1) {
  4530. var result = new Quaternion(0, 0, 0, 1.0);
  4531. this.multiplyToRef(q1, result);
  4532. return result;
  4533. };
  4534. /**
  4535. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4536. * @param q1 defines the second operand
  4537. * @param result defines the target quaternion
  4538. * @returns the current quaternion
  4539. */
  4540. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4541. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4542. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4543. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4544. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4545. result.copyFromFloats(x, y, z, w);
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4550. * @param q1 defines the second operand
  4551. * @returns the currentupdated quaternion
  4552. */
  4553. Quaternion.prototype.multiplyInPlace = function (q1) {
  4554. this.multiplyToRef(q1, this);
  4555. return this;
  4556. };
  4557. /**
  4558. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4559. * @param ref defines the target quaternion
  4560. * @returns the current quaternion
  4561. */
  4562. Quaternion.prototype.conjugateToRef = function (ref) {
  4563. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4564. return this;
  4565. };
  4566. /**
  4567. * Conjugates in place (1-q) the current quaternion
  4568. * @returns the current updated quaternion
  4569. */
  4570. Quaternion.prototype.conjugateInPlace = function () {
  4571. this.x *= -1;
  4572. this.y *= -1;
  4573. this.z *= -1;
  4574. return this;
  4575. };
  4576. /**
  4577. * Conjugates in place (1-q) the current quaternion
  4578. * @returns a new quaternion
  4579. */
  4580. Quaternion.prototype.conjugate = function () {
  4581. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4582. return result;
  4583. };
  4584. /**
  4585. * Gets length of current quaternion
  4586. * @returns the quaternion length (float)
  4587. */
  4588. Quaternion.prototype.length = function () {
  4589. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4590. };
  4591. /**
  4592. * Normalize in place the current quaternion
  4593. * @returns the current updated quaternion
  4594. */
  4595. Quaternion.prototype.normalize = function () {
  4596. var length = 1.0 / this.length();
  4597. this.x *= length;
  4598. this.y *= length;
  4599. this.z *= length;
  4600. this.w *= length;
  4601. return this;
  4602. };
  4603. /**
  4604. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4605. * @param order is a reserved parameter and is ignore for now
  4606. * @returns a new Vector3 containing the Euler angles
  4607. */
  4608. Quaternion.prototype.toEulerAngles = function (order) {
  4609. if (order === void 0) { order = "YZX"; }
  4610. var result = Vector3.Zero();
  4611. this.toEulerAnglesToRef(result, order);
  4612. return result;
  4613. };
  4614. /**
  4615. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4616. * @param result defines the vector which will be filled with the Euler angles
  4617. * @param order is a reserved parameter and is ignore for now
  4618. * @returns the current unchanged quaternion
  4619. */
  4620. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4621. if (order === void 0) { order = "YZX"; }
  4622. var qz = this.z;
  4623. var qx = this.x;
  4624. var qy = this.y;
  4625. var qw = this.w;
  4626. var sqw = qw * qw;
  4627. var sqz = qz * qz;
  4628. var sqx = qx * qx;
  4629. var sqy = qy * qy;
  4630. var zAxisY = qy * qz - qx * qw;
  4631. var limit = .4999999;
  4632. if (zAxisY < -limit) {
  4633. result.y = 2 * Math.atan2(qy, qw);
  4634. result.x = Math.PI / 2;
  4635. result.z = 0;
  4636. }
  4637. else if (zAxisY > limit) {
  4638. result.y = 2 * Math.atan2(qy, qw);
  4639. result.x = -Math.PI / 2;
  4640. result.z = 0;
  4641. }
  4642. else {
  4643. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4644. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4645. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4646. }
  4647. return this;
  4648. };
  4649. /**
  4650. * Updates the given rotation matrix with the current quaternion values
  4651. * @param result defines the target matrix
  4652. * @returns the current unchanged quaternion
  4653. */
  4654. Quaternion.prototype.toRotationMatrix = function (result) {
  4655. var xx = this.x * this.x;
  4656. var yy = this.y * this.y;
  4657. var zz = this.z * this.z;
  4658. var xy = this.x * this.y;
  4659. var zw = this.z * this.w;
  4660. var zx = this.z * this.x;
  4661. var yw = this.y * this.w;
  4662. var yz = this.y * this.z;
  4663. var xw = this.x * this.w;
  4664. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4665. result.m[1] = 2.0 * (xy + zw);
  4666. result.m[2] = 2.0 * (zx - yw);
  4667. result.m[3] = 0;
  4668. result.m[4] = 2.0 * (xy - zw);
  4669. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4670. result.m[6] = 2.0 * (yz + xw);
  4671. result.m[7] = 0;
  4672. result.m[8] = 2.0 * (zx + yw);
  4673. result.m[9] = 2.0 * (yz - xw);
  4674. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4675. result.m[11] = 0;
  4676. result.m[12] = 0;
  4677. result.m[13] = 0;
  4678. result.m[14] = 0;
  4679. result.m[15] = 1.0;
  4680. result._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Updates the current quaternion from the given rotation matrix values
  4685. * @param matrix defines the source matrix
  4686. * @returns the current updated quaternion
  4687. */
  4688. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4689. Quaternion.FromRotationMatrixToRef(matrix, this);
  4690. return this;
  4691. };
  4692. // Statics
  4693. /**
  4694. * Creates a new quaternion from a rotation matrix
  4695. * @param matrix defines the source matrix
  4696. * @returns a new quaternion created from the given rotation matrix values
  4697. */
  4698. Quaternion.FromRotationMatrix = function (matrix) {
  4699. var result = new Quaternion();
  4700. Quaternion.FromRotationMatrixToRef(matrix, result);
  4701. return result;
  4702. };
  4703. /**
  4704. * Updates the given quaternion with the given rotation matrix values
  4705. * @param matrix defines the source matrix
  4706. * @param result defines the target quaternion
  4707. */
  4708. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4709. var data = matrix.m;
  4710. var m11 = data[0], m12 = data[4], m13 = data[8];
  4711. var m21 = data[1], m22 = data[5], m23 = data[9];
  4712. var m31 = data[2], m32 = data[6], m33 = data[10];
  4713. var trace = m11 + m22 + m33;
  4714. var s;
  4715. if (trace > 0) {
  4716. s = 0.5 / Math.sqrt(trace + 1.0);
  4717. result.w = 0.25 / s;
  4718. result.x = (m32 - m23) * s;
  4719. result.y = (m13 - m31) * s;
  4720. result.z = (m21 - m12) * s;
  4721. }
  4722. else if (m11 > m22 && m11 > m33) {
  4723. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4724. result.w = (m32 - m23) / s;
  4725. result.x = 0.25 * s;
  4726. result.y = (m12 + m21) / s;
  4727. result.z = (m13 + m31) / s;
  4728. }
  4729. else if (m22 > m33) {
  4730. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4731. result.w = (m13 - m31) / s;
  4732. result.x = (m12 + m21) / s;
  4733. result.y = 0.25 * s;
  4734. result.z = (m23 + m32) / s;
  4735. }
  4736. else {
  4737. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4738. result.w = (m21 - m12) / s;
  4739. result.x = (m13 + m31) / s;
  4740. result.y = (m23 + m32) / s;
  4741. result.z = 0.25 * s;
  4742. }
  4743. };
  4744. /**
  4745. * Returns the dot product (float) between the quaternions "left" and "right"
  4746. * @param left defines the left operand
  4747. * @param right defines the right operand
  4748. * @returns the dot product
  4749. */
  4750. Quaternion.Dot = function (left, right) {
  4751. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4752. };
  4753. /**
  4754. * Checks if the two quaternions are close to each other
  4755. * @param quat0 defines the first quaternion to check
  4756. * @param quat1 defines the second quaternion to check
  4757. * @returns true if the two quaternions are close to each other
  4758. */
  4759. Quaternion.AreClose = function (quat0, quat1) {
  4760. var dot = Quaternion.Dot(quat0, quat1);
  4761. return dot >= 0;
  4762. };
  4763. /**
  4764. * Creates an empty quaternion
  4765. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4766. */
  4767. Quaternion.Zero = function () {
  4768. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4769. };
  4770. /**
  4771. * Inverse a given quaternion
  4772. * @param q defines the source quaternion
  4773. * @returns a new quaternion as the inverted current quaternion
  4774. */
  4775. Quaternion.Inverse = function (q) {
  4776. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4777. };
  4778. /**
  4779. * Creates an identity quaternion
  4780. * @returns the identity quaternion
  4781. */
  4782. Quaternion.Identity = function () {
  4783. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4784. };
  4785. /**
  4786. * Gets a boolean indicating if the given quaternion is identity
  4787. * @param quaternion defines the quaternion to check
  4788. * @returns true if the quaternion is identity
  4789. */
  4790. Quaternion.IsIdentity = function (quaternion) {
  4791. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4792. };
  4793. /**
  4794. * Creates a quaternion from a rotation around an axis
  4795. * @param axis defines the axis to use
  4796. * @param angle defines the angle to use
  4797. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4798. */
  4799. Quaternion.RotationAxis = function (axis, angle) {
  4800. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4801. };
  4802. /**
  4803. * Creates a rotation around an axis and stores it into the given quaternion
  4804. * @param axis defines the axis to use
  4805. * @param angle defines the angle to use
  4806. * @param result defines the target quaternion
  4807. * @returns the target quaternion
  4808. */
  4809. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4810. var sin = Math.sin(angle / 2);
  4811. axis.normalize();
  4812. result.w = Math.cos(angle / 2);
  4813. result.x = axis.x * sin;
  4814. result.y = axis.y * sin;
  4815. result.z = axis.z * sin;
  4816. return result;
  4817. };
  4818. /**
  4819. * Creates a new quaternion from data stored into an array
  4820. * @param array defines the data source
  4821. * @param offset defines the offset in the source array where the data starts
  4822. * @returns a new quaternion
  4823. */
  4824. Quaternion.FromArray = function (array, offset) {
  4825. if (!offset) {
  4826. offset = 0;
  4827. }
  4828. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4829. };
  4830. /**
  4831. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4832. * @param yaw defines the rotation around Y axis
  4833. * @param pitch defines the rotation around X axis
  4834. * @param roll defines the rotation around Z axis
  4835. * @returns the new quaternion
  4836. */
  4837. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4838. var q = new Quaternion();
  4839. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4840. return q;
  4841. };
  4842. /**
  4843. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4844. * @param yaw defines the rotation around Y axis
  4845. * @param pitch defines the rotation around X axis
  4846. * @param roll defines the rotation around Z axis
  4847. * @param result defines the target quaternion
  4848. */
  4849. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4850. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4851. var halfRoll = roll * 0.5;
  4852. var halfPitch = pitch * 0.5;
  4853. var halfYaw = yaw * 0.5;
  4854. var sinRoll = Math.sin(halfRoll);
  4855. var cosRoll = Math.cos(halfRoll);
  4856. var sinPitch = Math.sin(halfPitch);
  4857. var cosPitch = Math.cos(halfPitch);
  4858. var sinYaw = Math.sin(halfYaw);
  4859. var cosYaw = Math.cos(halfYaw);
  4860. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4861. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4862. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4863. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4864. };
  4865. /**
  4866. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4867. * @param alpha defines the rotation around first axis
  4868. * @param beta defines the rotation around second axis
  4869. * @param gamma defines the rotation around third axis
  4870. * @returns the new quaternion
  4871. */
  4872. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4873. var result = new Quaternion();
  4874. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4879. * @param alpha defines the rotation around first axis
  4880. * @param beta defines the rotation around second axis
  4881. * @param gamma defines the rotation around third axis
  4882. * @param result defines the target quaternion
  4883. */
  4884. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4885. // Produces a quaternion from Euler angles in the z-x-z orientation
  4886. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4887. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4888. var halfBeta = beta * 0.5;
  4889. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4890. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4891. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4892. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4893. };
  4894. /**
  4895. * 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)
  4896. * @param axis1 defines the first axis
  4897. * @param axis2 defines the second axis
  4898. * @param axis3 defines the third axis
  4899. * @returns the new quaternion
  4900. */
  4901. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4902. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4903. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4904. return quat;
  4905. };
  4906. /**
  4907. * 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
  4908. * @param axis1 defines the first axis
  4909. * @param axis2 defines the second axis
  4910. * @param axis3 defines the third axis
  4911. * @param ref defines the target quaternion
  4912. */
  4913. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4914. var rotMat = MathTmp.Matrix[0];
  4915. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4916. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4917. };
  4918. /**
  4919. * Interpolates between two quaternions
  4920. * @param left defines first quaternion
  4921. * @param right defines second quaternion
  4922. * @param amount defines the gradient to use
  4923. * @returns the new interpolated quaternion
  4924. */
  4925. Quaternion.Slerp = function (left, right, amount) {
  4926. var result = Quaternion.Identity();
  4927. Quaternion.SlerpToRef(left, right, amount, result);
  4928. return result;
  4929. };
  4930. /**
  4931. * Interpolates between two quaternions and stores it into a target quaternion
  4932. * @param left defines first quaternion
  4933. * @param right defines second quaternion
  4934. * @param amount defines the gradient to use
  4935. * @param result defines the target quaternion
  4936. */
  4937. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4938. var num2;
  4939. var num3;
  4940. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4941. var flag = false;
  4942. if (num4 < 0) {
  4943. flag = true;
  4944. num4 = -num4;
  4945. }
  4946. if (num4 > 0.999999) {
  4947. num3 = 1 - amount;
  4948. num2 = flag ? -amount : amount;
  4949. }
  4950. else {
  4951. var num5 = Math.acos(num4);
  4952. var num6 = (1.0 / Math.sin(num5));
  4953. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4954. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4955. }
  4956. result.x = (num3 * left.x) + (num2 * right.x);
  4957. result.y = (num3 * left.y) + (num2 * right.y);
  4958. result.z = (num3 * left.z) + (num2 * right.z);
  4959. result.w = (num3 * left.w) + (num2 * right.w);
  4960. };
  4961. /**
  4962. * Interpolate between two quaternions using Hermite interpolation
  4963. * @param value1 defines first quaternion
  4964. * @param tangent1 defines the incoming tangent
  4965. * @param value2 defines second quaternion
  4966. * @param tangent2 defines the outgoing tangent
  4967. * @param amount defines the target quaternion
  4968. * @returns the new interpolated quaternion
  4969. */
  4970. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4971. var squared = amount * amount;
  4972. var cubed = amount * squared;
  4973. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4974. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4975. var part3 = (cubed - (2.0 * squared)) + amount;
  4976. var part4 = cubed - squared;
  4977. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4978. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4979. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4980. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4981. return new Quaternion(x, y, z, w);
  4982. };
  4983. return Quaternion;
  4984. }());
  4985. BABYLON.Quaternion = Quaternion;
  4986. /**
  4987. * Class used to store matrix data (4x4)
  4988. */
  4989. var Matrix = /** @class */ (function () {
  4990. /**
  4991. * Creates an empty matrix (filled with zeros)
  4992. */
  4993. function Matrix() {
  4994. this._isIdentity = false;
  4995. this._isIdentityDirty = true;
  4996. /**
  4997. * Gets or sets the internal data of the matrix
  4998. */
  4999. this.m = new Float32Array(16);
  5000. this._markAsUpdated();
  5001. }
  5002. /** @hidden */
  5003. Matrix.prototype._markAsUpdated = function () {
  5004. this.updateFlag = Matrix._updateFlagSeed++;
  5005. this._isIdentityDirty = true;
  5006. };
  5007. // Properties
  5008. /**
  5009. * Check if the current matrix is indentity
  5010. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5011. * @returns true is the matrix is the identity matrix
  5012. */
  5013. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5014. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5015. if (this._isIdentityDirty) {
  5016. this._isIdentityDirty = false;
  5017. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5018. this._isIdentity = false;
  5019. }
  5020. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5021. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5022. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5023. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5024. this._isIdentity = false;
  5025. }
  5026. else {
  5027. this._isIdentity = true;
  5028. }
  5029. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5030. this._isIdentity = false;
  5031. }
  5032. }
  5033. return this._isIdentity;
  5034. };
  5035. /**
  5036. * Gets the determinant of the matrix
  5037. * @returns the matrix determinant
  5038. */
  5039. Matrix.prototype.determinant = function () {
  5040. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5041. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5042. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5043. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5044. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5045. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5046. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5047. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5048. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5049. };
  5050. // Methods
  5051. /**
  5052. * Returns the matrix as a Float32Array
  5053. * @returns the matrix underlying array
  5054. */
  5055. Matrix.prototype.toArray = function () {
  5056. return this.m;
  5057. };
  5058. /**
  5059. * Returns the matrix as a Float32Array
  5060. * @returns the matrix underlying array.
  5061. */
  5062. Matrix.prototype.asArray = function () {
  5063. return this.toArray();
  5064. };
  5065. /**
  5066. * Inverts the current matrix in place
  5067. * @returns the current inverted matrix
  5068. */
  5069. Matrix.prototype.invert = function () {
  5070. this.invertToRef(this);
  5071. return this;
  5072. };
  5073. /**
  5074. * Sets all the matrix elements to zero
  5075. * @returns the current matrix
  5076. */
  5077. Matrix.prototype.reset = function () {
  5078. for (var index = 0; index < 16; index++) {
  5079. this.m[index] = 0.0;
  5080. }
  5081. this._markAsUpdated();
  5082. return this;
  5083. };
  5084. /**
  5085. * Adds the current matrix with a second one
  5086. * @param other defines the matrix to add
  5087. * @returns a new matrix as the addition of the current matrix and the given one
  5088. */
  5089. Matrix.prototype.add = function (other) {
  5090. var result = new Matrix();
  5091. this.addToRef(other, result);
  5092. return result;
  5093. };
  5094. /**
  5095. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5096. * @param other defines the matrix to add
  5097. * @param result defines the target matrix
  5098. * @returns the current matrix
  5099. */
  5100. Matrix.prototype.addToRef = function (other, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = this.m[index] + other.m[index];
  5103. }
  5104. result._markAsUpdated();
  5105. return this;
  5106. };
  5107. /**
  5108. * Adds in place the given matrix to the current matrix
  5109. * @param other defines the second operand
  5110. * @returns the current updated matrix
  5111. */
  5112. Matrix.prototype.addToSelf = function (other) {
  5113. for (var index = 0; index < 16; index++) {
  5114. this.m[index] += other.m[index];
  5115. }
  5116. this._markAsUpdated();
  5117. return this;
  5118. };
  5119. /**
  5120. * Sets the given matrix to the current inverted Matrix
  5121. * @param other defines the target matrix
  5122. * @returns the unmodified current matrix
  5123. */
  5124. Matrix.prototype.invertToRef = function (other) {
  5125. var l1 = this.m[0];
  5126. var l2 = this.m[1];
  5127. var l3 = this.m[2];
  5128. var l4 = this.m[3];
  5129. var l5 = this.m[4];
  5130. var l6 = this.m[5];
  5131. var l7 = this.m[6];
  5132. var l8 = this.m[7];
  5133. var l9 = this.m[8];
  5134. var l10 = this.m[9];
  5135. var l11 = this.m[10];
  5136. var l12 = this.m[11];
  5137. var l13 = this.m[12];
  5138. var l14 = this.m[13];
  5139. var l15 = this.m[14];
  5140. var l16 = this.m[15];
  5141. var l17 = (l11 * l16) - (l12 * l15);
  5142. var l18 = (l10 * l16) - (l12 * l14);
  5143. var l19 = (l10 * l15) - (l11 * l14);
  5144. var l20 = (l9 * l16) - (l12 * l13);
  5145. var l21 = (l9 * l15) - (l11 * l13);
  5146. var l22 = (l9 * l14) - (l10 * l13);
  5147. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5148. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5149. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5150. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5151. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5152. var l28 = (l7 * l16) - (l8 * l15);
  5153. var l29 = (l6 * l16) - (l8 * l14);
  5154. var l30 = (l6 * l15) - (l7 * l14);
  5155. var l31 = (l5 * l16) - (l8 * l13);
  5156. var l32 = (l5 * l15) - (l7 * l13);
  5157. var l33 = (l5 * l14) - (l6 * l13);
  5158. var l34 = (l7 * l12) - (l8 * l11);
  5159. var l35 = (l6 * l12) - (l8 * l10);
  5160. var l36 = (l6 * l11) - (l7 * l10);
  5161. var l37 = (l5 * l12) - (l8 * l9);
  5162. var l38 = (l5 * l11) - (l7 * l9);
  5163. var l39 = (l5 * l10) - (l6 * l9);
  5164. other.m[0] = l23 * l27;
  5165. other.m[4] = l24 * l27;
  5166. other.m[8] = l25 * l27;
  5167. other.m[12] = l26 * l27;
  5168. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5169. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5170. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5171. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5172. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5173. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5174. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5175. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5176. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5177. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5178. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5179. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5180. other._markAsUpdated();
  5181. return this;
  5182. };
  5183. /**
  5184. * Inserts the translation vector (using 3 floats) in the current matrix
  5185. * @param x defines the 1st component of the translation
  5186. * @param y defines the 2nd component of the translation
  5187. * @param z defines the 3rd component of the translation
  5188. * @returns the current updated matrix
  5189. */
  5190. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5191. this.m[12] = x;
  5192. this.m[13] = y;
  5193. this.m[14] = z;
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Inserts the translation vector in the current matrix
  5199. * @param vector3 defines the translation to insert
  5200. * @returns the current updated matrix
  5201. */
  5202. Matrix.prototype.setTranslation = function (vector3) {
  5203. this.m[12] = vector3.x;
  5204. this.m[13] = vector3.y;
  5205. this.m[14] = vector3.z;
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Gets the translation value of the current matrix
  5211. * @returns a new Vector3 as the extracted translation from the matrix
  5212. */
  5213. Matrix.prototype.getTranslation = function () {
  5214. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5215. };
  5216. /**
  5217. * Fill a Vector3 with the extracted translation from the matrix
  5218. * @param result defines the Vector3 where to store the translation
  5219. * @returns the current matrix
  5220. */
  5221. Matrix.prototype.getTranslationToRef = function (result) {
  5222. result.x = this.m[12];
  5223. result.y = this.m[13];
  5224. result.z = this.m[14];
  5225. return this;
  5226. };
  5227. /**
  5228. * Remove rotation and scaling part from the matrix
  5229. * @returns the updated matrix
  5230. */
  5231. Matrix.prototype.removeRotationAndScaling = function () {
  5232. this.setRowFromFloats(0, 1, 0, 0, 0);
  5233. this.setRowFromFloats(1, 0, 1, 0, 0);
  5234. this.setRowFromFloats(2, 0, 0, 1, 0);
  5235. return this;
  5236. };
  5237. /**
  5238. * Multiply two matrices
  5239. * @param other defines the second operand
  5240. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5241. */
  5242. Matrix.prototype.multiply = function (other) {
  5243. var result = new Matrix();
  5244. this.multiplyToRef(other, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Copy the current matrix from the given one
  5249. * @param other defines the source matrix
  5250. * @returns the current updated matrix
  5251. */
  5252. Matrix.prototype.copyFrom = function (other) {
  5253. for (var index = 0; index < 16; index++) {
  5254. this.m[index] = other.m[index];
  5255. }
  5256. this._markAsUpdated();
  5257. return this;
  5258. };
  5259. /**
  5260. * Populates the given array from the starting index with the current matrix values
  5261. * @param array defines the target array
  5262. * @param offset defines the offset in the target array where to start storing values
  5263. * @returns the current matrix
  5264. */
  5265. Matrix.prototype.copyToArray = function (array, offset) {
  5266. if (offset === void 0) { offset = 0; }
  5267. for (var index = 0; index < 16; index++) {
  5268. array[offset + index] = this.m[index];
  5269. }
  5270. return this;
  5271. };
  5272. /**
  5273. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5274. * @param other defines the second operand
  5275. * @param result defines the matrix where to store the multiplication
  5276. * @returns the current matrix
  5277. */
  5278. Matrix.prototype.multiplyToRef = function (other, result) {
  5279. this.multiplyToArray(other, result.m, 0);
  5280. result._markAsUpdated();
  5281. return this;
  5282. };
  5283. /**
  5284. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5285. * @param other defines the second operand
  5286. * @param result defines the array where to store the multiplication
  5287. * @param offset defines the offset in the target array where to start storing values
  5288. * @returns the current matrix
  5289. */
  5290. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5291. var tm0 = this.m[0];
  5292. var tm1 = this.m[1];
  5293. var tm2 = this.m[2];
  5294. var tm3 = this.m[3];
  5295. var tm4 = this.m[4];
  5296. var tm5 = this.m[5];
  5297. var tm6 = this.m[6];
  5298. var tm7 = this.m[7];
  5299. var tm8 = this.m[8];
  5300. var tm9 = this.m[9];
  5301. var tm10 = this.m[10];
  5302. var tm11 = this.m[11];
  5303. var tm12 = this.m[12];
  5304. var tm13 = this.m[13];
  5305. var tm14 = this.m[14];
  5306. var tm15 = this.m[15];
  5307. var om0 = other.m[0];
  5308. var om1 = other.m[1];
  5309. var om2 = other.m[2];
  5310. var om3 = other.m[3];
  5311. var om4 = other.m[4];
  5312. var om5 = other.m[5];
  5313. var om6 = other.m[6];
  5314. var om7 = other.m[7];
  5315. var om8 = other.m[8];
  5316. var om9 = other.m[9];
  5317. var om10 = other.m[10];
  5318. var om11 = other.m[11];
  5319. var om12 = other.m[12];
  5320. var om13 = other.m[13];
  5321. var om14 = other.m[14];
  5322. var om15 = other.m[15];
  5323. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5324. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5325. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5326. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5327. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5328. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5329. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5330. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5331. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5332. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5333. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5334. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5335. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5336. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5337. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5338. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5339. return this;
  5340. };
  5341. /**
  5342. * Check equality between this matrix and a second one
  5343. * @param value defines the second matrix to compare
  5344. * @returns true is the current matrix and the given one values are strictly equal
  5345. */
  5346. Matrix.prototype.equals = function (value) {
  5347. return value &&
  5348. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5349. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5350. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5351. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5352. };
  5353. /**
  5354. * Clone the current matrix
  5355. * @returns a new matrix from the current matrix
  5356. */
  5357. Matrix.prototype.clone = function () {
  5358. 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]);
  5359. };
  5360. /**
  5361. * Returns the name of the current matrix class
  5362. * @returns the string "Matrix"
  5363. */
  5364. Matrix.prototype.getClassName = function () {
  5365. return "Matrix";
  5366. };
  5367. /**
  5368. * Gets the hash code of the current matrix
  5369. * @returns the hash code
  5370. */
  5371. Matrix.prototype.getHashCode = function () {
  5372. var hash = this.m[0] || 0;
  5373. for (var i = 1; i < 16; i++) {
  5374. hash = (hash * 397) ^ (this.m[i] || 0);
  5375. }
  5376. return hash;
  5377. };
  5378. /**
  5379. * Decomposes the current Matrix into a translation, rotation and scaling components
  5380. * @param scale defines the scale vector3 given as a reference to update
  5381. * @param rotation defines the rotation quaternion given as a reference to update
  5382. * @param translation defines the translation vector3 given as a reference to update
  5383. * @returns true if operation was successful
  5384. */
  5385. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5386. if (translation) {
  5387. translation.x = this.m[12];
  5388. translation.y = this.m[13];
  5389. translation.z = this.m[14];
  5390. }
  5391. scale = scale || MathTmp.Vector3[0];
  5392. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5393. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5394. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5395. if (this.determinant() <= 0) {
  5396. scale.y *= -1;
  5397. }
  5398. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5399. if (rotation) {
  5400. rotation.x = 0;
  5401. rotation.y = 0;
  5402. rotation.z = 0;
  5403. rotation.w = 1;
  5404. }
  5405. return false;
  5406. }
  5407. if (rotation) {
  5408. 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]);
  5409. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5410. }
  5411. return true;
  5412. };
  5413. /**
  5414. * Gets specific row of the matrix
  5415. * @param index defines the number of the row to get
  5416. * @returns the index-th row of the current matrix as a new Vector4
  5417. */
  5418. Matrix.prototype.getRow = function (index) {
  5419. if (index < 0 || index > 3) {
  5420. return null;
  5421. }
  5422. var i = index * 4;
  5423. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5424. };
  5425. /**
  5426. * Sets the index-th row of the current matrix to the vector4 values
  5427. * @param index defines the number of the row to set
  5428. * @param row defines the target vector4
  5429. * @returns the updated current matrix
  5430. */
  5431. Matrix.prototype.setRow = function (index, row) {
  5432. if (index < 0 || index > 3) {
  5433. return this;
  5434. }
  5435. var i = index * 4;
  5436. this.m[i + 0] = row.x;
  5437. this.m[i + 1] = row.y;
  5438. this.m[i + 2] = row.z;
  5439. this.m[i + 3] = row.w;
  5440. this._markAsUpdated();
  5441. return this;
  5442. };
  5443. /**
  5444. * Compute the transpose of the matrix
  5445. * @returns the new transposed matrix
  5446. */
  5447. Matrix.prototype.transpose = function () {
  5448. return Matrix.Transpose(this);
  5449. };
  5450. /**
  5451. * Compute the transpose of the matrix and store it in a given matrix
  5452. * @param result defines the target matrix
  5453. * @returns the current matrix
  5454. */
  5455. Matrix.prototype.transposeToRef = function (result) {
  5456. Matrix.TransposeToRef(this, result);
  5457. return this;
  5458. };
  5459. /**
  5460. * Sets the index-th row of the current matrix with the given 4 x float values
  5461. * @param index defines the row index
  5462. * @param x defines the x component to set
  5463. * @param y defines the y component to set
  5464. * @param z defines the z component to set
  5465. * @param w defines the w component to set
  5466. * @returns the updated current matrix
  5467. */
  5468. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5469. if (index < 0 || index > 3) {
  5470. return this;
  5471. }
  5472. var i = index * 4;
  5473. this.m[i + 0] = x;
  5474. this.m[i + 1] = y;
  5475. this.m[i + 2] = z;
  5476. this.m[i + 3] = w;
  5477. this._markAsUpdated();
  5478. return this;
  5479. };
  5480. /**
  5481. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5482. * @param scale defines the scale factor
  5483. * @returns a new matrix
  5484. */
  5485. Matrix.prototype.scale = function (scale) {
  5486. var result = new Matrix();
  5487. this.scaleToRef(scale, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Scale the current matrix values by a factor to a given result matrix
  5492. * @param scale defines the scale factor
  5493. * @param result defines the matrix to store the result
  5494. * @returns the current matrix
  5495. */
  5496. Matrix.prototype.scaleToRef = function (scale, result) {
  5497. for (var index = 0; index < 16; index++) {
  5498. result.m[index] = this.m[index] * scale;
  5499. }
  5500. result._markAsUpdated();
  5501. return this;
  5502. };
  5503. /**
  5504. * Scale the current matrix values by a factor and add the result to a given matrix
  5505. * @param scale defines the scale factor
  5506. * @param result defines the Matrix to store the result
  5507. * @returns the current matrix
  5508. */
  5509. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5510. for (var index = 0; index < 16; index++) {
  5511. result.m[index] += this.m[index] * scale;
  5512. }
  5513. result._markAsUpdated();
  5514. return this;
  5515. };
  5516. /**
  5517. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5518. * @param ref matrix to store the result
  5519. */
  5520. Matrix.prototype.toNormalMatrix = function (ref) {
  5521. this.invertToRef(ref);
  5522. ref.transpose();
  5523. var m = ref.m;
  5524. 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);
  5525. };
  5526. /**
  5527. * Gets only rotation part of the current matrix
  5528. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5529. */
  5530. Matrix.prototype.getRotationMatrix = function () {
  5531. var result = Matrix.Identity();
  5532. this.getRotationMatrixToRef(result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5537. * @param result defines the target matrix to store data to
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5541. var m = this.m;
  5542. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5543. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5544. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5545. if (this.determinant() <= 0) {
  5546. sy *= -1;
  5547. }
  5548. if (sx === 0 || sy === 0 || sz === 0) {
  5549. Matrix.IdentityToRef(result);
  5550. }
  5551. else {
  5552. 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);
  5553. }
  5554. return this;
  5555. };
  5556. // Statics
  5557. /**
  5558. * Creates a matrix from an array
  5559. * @param array defines the source array
  5560. * @param offset defines an offset in the source array
  5561. * @returns a new Matrix set from the starting index of the given array
  5562. */
  5563. Matrix.FromArray = function (array, offset) {
  5564. var result = new Matrix();
  5565. if (!offset) {
  5566. offset = 0;
  5567. }
  5568. Matrix.FromArrayToRef(array, offset, result);
  5569. return result;
  5570. };
  5571. /**
  5572. * Copy the content of an array into a given matrix
  5573. * @param array defines the source array
  5574. * @param offset defines an offset in the source array
  5575. * @param result defines the target matrix
  5576. */
  5577. Matrix.FromArrayToRef = function (array, offset, result) {
  5578. for (var index = 0; index < 16; index++) {
  5579. result.m[index] = array[index + offset];
  5580. }
  5581. result._markAsUpdated();
  5582. };
  5583. /**
  5584. * Stores an array into a matrix after having multiplied each component by a given factor
  5585. * @param array defines the source array
  5586. * @param offset defines the offset in the source array
  5587. * @param scale defines the scaling factor
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5591. for (var index = 0; index < 16; index++) {
  5592. result.m[index] = array[index + offset] * scale;
  5593. }
  5594. result._markAsUpdated();
  5595. };
  5596. /**
  5597. * Stores a list of values (16) inside a given matrix
  5598. * @param initialM11 defines 1st value of 1st row
  5599. * @param initialM12 defines 2nd value of 1st row
  5600. * @param initialM13 defines 3rd value of 1st row
  5601. * @param initialM14 defines 4th value of 1st row
  5602. * @param initialM21 defines 1st value of 2nd row
  5603. * @param initialM22 defines 2nd value of 2nd row
  5604. * @param initialM23 defines 3rd value of 2nd row
  5605. * @param initialM24 defines 4th value of 2nd row
  5606. * @param initialM31 defines 1st value of 3rd row
  5607. * @param initialM32 defines 2nd value of 3rd row
  5608. * @param initialM33 defines 3rd value of 3rd row
  5609. * @param initialM34 defines 4th value of 3rd row
  5610. * @param initialM41 defines 1st value of 4th row
  5611. * @param initialM42 defines 2nd value of 4th row
  5612. * @param initialM43 defines 3rd value of 4th row
  5613. * @param initialM44 defines 4th value of 4th row
  5614. * @param result defines the target matrix
  5615. */
  5616. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5617. result.m[0] = initialM11;
  5618. result.m[1] = initialM12;
  5619. result.m[2] = initialM13;
  5620. result.m[3] = initialM14;
  5621. result.m[4] = initialM21;
  5622. result.m[5] = initialM22;
  5623. result.m[6] = initialM23;
  5624. result.m[7] = initialM24;
  5625. result.m[8] = initialM31;
  5626. result.m[9] = initialM32;
  5627. result.m[10] = initialM33;
  5628. result.m[11] = initialM34;
  5629. result.m[12] = initialM41;
  5630. result.m[13] = initialM42;
  5631. result.m[14] = initialM43;
  5632. result.m[15] = initialM44;
  5633. result._markAsUpdated();
  5634. };
  5635. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5636. /**
  5637. * Gets an identity matrix that must not be updated
  5638. */
  5639. get: function () {
  5640. return Matrix._identityReadOnly;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. /**
  5646. * Creates new matrix from a list of values (16)
  5647. * @param initialM11 defines 1st value of 1st row
  5648. * @param initialM12 defines 2nd value of 1st row
  5649. * @param initialM13 defines 3rd value of 1st row
  5650. * @param initialM14 defines 4th value of 1st row
  5651. * @param initialM21 defines 1st value of 2nd row
  5652. * @param initialM22 defines 2nd value of 2nd row
  5653. * @param initialM23 defines 3rd value of 2nd row
  5654. * @param initialM24 defines 4th value of 2nd row
  5655. * @param initialM31 defines 1st value of 3rd row
  5656. * @param initialM32 defines 2nd value of 3rd row
  5657. * @param initialM33 defines 3rd value of 3rd row
  5658. * @param initialM34 defines 4th value of 3rd row
  5659. * @param initialM41 defines 1st value of 4th row
  5660. * @param initialM42 defines 2nd value of 4th row
  5661. * @param initialM43 defines 3rd value of 4th row
  5662. * @param initialM44 defines 4th value of 4th row
  5663. * @returns the new matrix
  5664. */
  5665. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5666. var result = new Matrix();
  5667. result.m[0] = initialM11;
  5668. result.m[1] = initialM12;
  5669. result.m[2] = initialM13;
  5670. result.m[3] = initialM14;
  5671. result.m[4] = initialM21;
  5672. result.m[5] = initialM22;
  5673. result.m[6] = initialM23;
  5674. result.m[7] = initialM24;
  5675. result.m[8] = initialM31;
  5676. result.m[9] = initialM32;
  5677. result.m[10] = initialM33;
  5678. result.m[11] = initialM34;
  5679. result.m[12] = initialM41;
  5680. result.m[13] = initialM42;
  5681. result.m[14] = initialM43;
  5682. result.m[15] = initialM44;
  5683. return result;
  5684. };
  5685. /**
  5686. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5687. * @param scale defines the scale vector3
  5688. * @param rotation defines the rotation quaternion
  5689. * @param translation defines the translation vector3
  5690. * @returns a new matrix
  5691. */
  5692. Matrix.Compose = function (scale, rotation, translation) {
  5693. var result = Matrix.Identity();
  5694. Matrix.ComposeToRef(scale, rotation, translation, result);
  5695. return result;
  5696. };
  5697. /**
  5698. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5699. * @param scale defines the scale vector3
  5700. * @param rotation defines the rotation quaternion
  5701. * @param translation defines the translation vector3
  5702. * @param result defines the target matrix
  5703. */
  5704. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5705. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5706. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5707. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5708. result.setTranslation(translation);
  5709. };
  5710. /**
  5711. * Creates a new identity matrix
  5712. * @returns a new identity matrix
  5713. */
  5714. Matrix.Identity = function () {
  5715. 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);
  5716. };
  5717. /**
  5718. * Creates a new identity matrix and stores the result in a given matrix
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.IdentityToRef = function (result) {
  5722. 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);
  5723. };
  5724. /**
  5725. * Creates a new zero matrix
  5726. * @returns a new zero matrix
  5727. */
  5728. Matrix.Zero = function () {
  5729. 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);
  5730. };
  5731. /**
  5732. * Creates a new rotation matrix for "angle" radians around the X axis
  5733. * @param angle defines the angle (in radians) to use
  5734. * @return the new matrix
  5735. */
  5736. Matrix.RotationX = function (angle) {
  5737. var result = new Matrix();
  5738. Matrix.RotationXToRef(angle, result);
  5739. return result;
  5740. };
  5741. /**
  5742. * Creates a new matrix as the invert of a given matrix
  5743. * @param source defines the source matrix
  5744. * @returns the new matrix
  5745. */
  5746. Matrix.Invert = function (source) {
  5747. var result = new Matrix();
  5748. source.invertToRef(result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5753. * @param angle defines the angle (in radians) to use
  5754. * @param result defines the target matrix
  5755. */
  5756. Matrix.RotationXToRef = function (angle, result) {
  5757. var s = Math.sin(angle);
  5758. var c = Math.cos(angle);
  5759. result.m[0] = 1.0;
  5760. result.m[15] = 1.0;
  5761. result.m[5] = c;
  5762. result.m[10] = c;
  5763. result.m[9] = -s;
  5764. result.m[6] = s;
  5765. result.m[1] = 0.0;
  5766. result.m[2] = 0.0;
  5767. result.m[3] = 0.0;
  5768. result.m[4] = 0.0;
  5769. result.m[7] = 0.0;
  5770. result.m[8] = 0.0;
  5771. result.m[11] = 0.0;
  5772. result.m[12] = 0.0;
  5773. result.m[13] = 0.0;
  5774. result.m[14] = 0.0;
  5775. result._markAsUpdated();
  5776. };
  5777. /**
  5778. * Creates a new rotation matrix for "angle" radians around the Y axis
  5779. * @param angle defines the angle (in radians) to use
  5780. * @return the new matrix
  5781. */
  5782. Matrix.RotationY = function (angle) {
  5783. var result = new Matrix();
  5784. Matrix.RotationYToRef(angle, result);
  5785. return result;
  5786. };
  5787. /**
  5788. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5789. * @param angle defines the angle (in radians) to use
  5790. * @param result defines the target matrix
  5791. */
  5792. Matrix.RotationYToRef = function (angle, result) {
  5793. var s = Math.sin(angle);
  5794. var c = Math.cos(angle);
  5795. result.m[5] = 1.0;
  5796. result.m[15] = 1.0;
  5797. result.m[0] = c;
  5798. result.m[2] = -s;
  5799. result.m[8] = s;
  5800. result.m[10] = c;
  5801. result.m[1] = 0.0;
  5802. result.m[3] = 0.0;
  5803. result.m[4] = 0.0;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[9] = 0.0;
  5807. result.m[11] = 0.0;
  5808. result.m[12] = 0.0;
  5809. result.m[13] = 0.0;
  5810. result.m[14] = 0.0;
  5811. result._markAsUpdated();
  5812. };
  5813. /**
  5814. * Creates a new rotation matrix for "angle" radians around the Z axis
  5815. * @param angle defines the angle (in radians) to use
  5816. * @return the new matrix
  5817. */
  5818. Matrix.RotationZ = function (angle) {
  5819. var result = new Matrix();
  5820. Matrix.RotationZToRef(angle, result);
  5821. return result;
  5822. };
  5823. /**
  5824. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5825. * @param angle defines the angle (in radians) to use
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.RotationZToRef = function (angle, result) {
  5829. var s = Math.sin(angle);
  5830. var c = Math.cos(angle);
  5831. result.m[10] = 1.0;
  5832. result.m[15] = 1.0;
  5833. result.m[0] = c;
  5834. result.m[1] = s;
  5835. result.m[4] = -s;
  5836. result.m[5] = c;
  5837. result.m[2] = 0.0;
  5838. result.m[3] = 0.0;
  5839. result.m[6] = 0.0;
  5840. result.m[7] = 0.0;
  5841. result.m[8] = 0.0;
  5842. result.m[9] = 0.0;
  5843. result.m[11] = 0.0;
  5844. result.m[12] = 0.0;
  5845. result.m[13] = 0.0;
  5846. result.m[14] = 0.0;
  5847. result._markAsUpdated();
  5848. };
  5849. /**
  5850. * Creates a new rotation matrix for "angle" radians around the given axis
  5851. * @param axis defines the axis to use
  5852. * @param angle defines the angle (in radians) to use
  5853. * @return the new matrix
  5854. */
  5855. Matrix.RotationAxis = function (axis, angle) {
  5856. var result = Matrix.Zero();
  5857. Matrix.RotationAxisToRef(axis, angle, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5862. * @param axis defines the axis to use
  5863. * @param angle defines the angle (in radians) to use
  5864. * @param result defines the target matrix
  5865. */
  5866. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5867. var s = Math.sin(-angle);
  5868. var c = Math.cos(-angle);
  5869. var c1 = 1 - c;
  5870. axis.normalize();
  5871. result.m[0] = (axis.x * axis.x) * c1 + c;
  5872. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5873. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5874. result.m[3] = 0.0;
  5875. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5876. result.m[5] = (axis.y * axis.y) * c1 + c;
  5877. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5878. result.m[7] = 0.0;
  5879. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5880. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5881. result.m[10] = (axis.z * axis.z) * c1 + c;
  5882. result.m[11] = 0.0;
  5883. result.m[15] = 1.0;
  5884. result._markAsUpdated();
  5885. };
  5886. /**
  5887. * Creates a rotation matrix
  5888. * @param yaw defines the yaw angle in radians (Y axis)
  5889. * @param pitch defines the pitch angle in radians (X axis)
  5890. * @param roll defines the roll angle in radians (X axis)
  5891. * @returns the new rotation matrix
  5892. */
  5893. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a rotation matrix and stores it in a given matrix
  5900. * @param yaw defines the yaw angle in radians (Y axis)
  5901. * @param pitch defines the pitch angle in radians (X axis)
  5902. * @param roll defines the roll angle in radians (X axis)
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5906. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5907. this._tempQuaternion.toRotationMatrix(result);
  5908. };
  5909. /**
  5910. * Creates a scaling matrix
  5911. * @param x defines the scale factor on X axis
  5912. * @param y defines the scale factor on Y axis
  5913. * @param z defines the scale factor on Z axis
  5914. * @returns the new matrix
  5915. */
  5916. Matrix.Scaling = function (x, y, z) {
  5917. var result = Matrix.Zero();
  5918. Matrix.ScalingToRef(x, y, z, result);
  5919. return result;
  5920. };
  5921. /**
  5922. * Creates a scaling matrix and stores it in a given matrix
  5923. * @param x defines the scale factor on X axis
  5924. * @param y defines the scale factor on Y axis
  5925. * @param z defines the scale factor on Z axis
  5926. * @param result defines the target matrix
  5927. */
  5928. Matrix.ScalingToRef = function (x, y, z, result) {
  5929. result.m[0] = x;
  5930. result.m[1] = 0.0;
  5931. result.m[2] = 0.0;
  5932. result.m[3] = 0.0;
  5933. result.m[4] = 0.0;
  5934. result.m[5] = y;
  5935. result.m[6] = 0.0;
  5936. result.m[7] = 0.0;
  5937. result.m[8] = 0.0;
  5938. result.m[9] = 0.0;
  5939. result.m[10] = z;
  5940. result.m[11] = 0.0;
  5941. result.m[12] = 0.0;
  5942. result.m[13] = 0.0;
  5943. result.m[14] = 0.0;
  5944. result.m[15] = 1.0;
  5945. result._markAsUpdated();
  5946. };
  5947. /**
  5948. * Creates a translation matrix
  5949. * @param x defines the translation on X axis
  5950. * @param y defines the translation on Y axis
  5951. * @param z defines the translationon Z axis
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Translation = function (x, y, z) {
  5955. var result = Matrix.Identity();
  5956. Matrix.TranslationToRef(x, y, z, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a translation matrix and stores it in a given matrix
  5961. * @param x defines the translation on X axis
  5962. * @param y defines the translation on Y axis
  5963. * @param z defines the translationon Z axis
  5964. * @param result defines the target matrix
  5965. */
  5966. Matrix.TranslationToRef = function (x, y, z, result) {
  5967. 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);
  5968. };
  5969. /**
  5970. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5971. * @param startValue defines the start value
  5972. * @param endValue defines the end value
  5973. * @param gradient defines the gradient factor
  5974. * @returns the new matrix
  5975. */
  5976. Matrix.Lerp = function (startValue, endValue, gradient) {
  5977. var result = Matrix.Zero();
  5978. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5979. return result;
  5980. };
  5981. /**
  5982. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5983. * @param startValue defines the start value
  5984. * @param endValue defines the end value
  5985. * @param gradient defines the gradient factor
  5986. * @param result defines the Matrix object where to store data
  5987. */
  5988. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5989. for (var index = 0; index < 16; index++) {
  5990. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5991. }
  5992. result._markAsUpdated();
  5993. };
  5994. /**
  5995. * Builds a new matrix whose values are computed by:
  5996. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5997. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5998. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5999. * @param startValue defines the first matrix
  6000. * @param endValue defines the second matrix
  6001. * @param gradient defines the gradient between the two matrices
  6002. * @returns the new matrix
  6003. */
  6004. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6005. var result = Matrix.Zero();
  6006. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Update a matrix to values which are computed by:
  6011. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6012. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6013. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6014. * @param startValue defines the first matrix
  6015. * @param endValue defines the second matrix
  6016. * @param gradient defines the gradient between the two matrices
  6017. * @param result defines the target matrix
  6018. */
  6019. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6020. var startScale = MathTmp.Vector3[0];
  6021. var startRotation = MathTmp.Quaternion[0];
  6022. var startTranslation = MathTmp.Vector3[1];
  6023. startValue.decompose(startScale, startRotation, startTranslation);
  6024. var endScale = MathTmp.Vector3[2];
  6025. var endRotation = MathTmp.Quaternion[1];
  6026. var endTranslation = MathTmp.Vector3[3];
  6027. endValue.decompose(endScale, endRotation, endTranslation);
  6028. var resultScale = MathTmp.Vector3[4];
  6029. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6030. var resultRotation = MathTmp.Quaternion[2];
  6031. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6032. var resultTranslation = MathTmp.Vector3[5];
  6033. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6034. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6035. };
  6036. /**
  6037. * 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"
  6038. * This function works in left handed mode
  6039. * @param eye defines the final position of the entity
  6040. * @param target defines where the entity should look at
  6041. * @param up defines the up vector for the entity
  6042. * @returns the new matrix
  6043. */
  6044. Matrix.LookAtLH = function (eye, target, up) {
  6045. var result = Matrix.Zero();
  6046. Matrix.LookAtLHToRef(eye, target, up, result);
  6047. return result;
  6048. };
  6049. /**
  6050. * 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".
  6051. * This function works in left handed mode
  6052. * @param eye defines the final position of the entity
  6053. * @param target defines where the entity should look at
  6054. * @param up defines the up vector for the entity
  6055. * @param result defines the target matrix
  6056. */
  6057. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6058. // Z axis
  6059. target.subtractToRef(eye, this._zAxis);
  6060. this._zAxis.normalize();
  6061. // X axis
  6062. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6063. if (this._xAxis.lengthSquared() === 0) {
  6064. this._xAxis.x = 1.0;
  6065. }
  6066. else {
  6067. this._xAxis.normalize();
  6068. }
  6069. // Y axis
  6070. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6071. this._yAxis.normalize();
  6072. // Eye angles
  6073. var ex = -Vector3.Dot(this._xAxis, eye);
  6074. var ey = -Vector3.Dot(this._yAxis, eye);
  6075. var ez = -Vector3.Dot(this._zAxis, eye);
  6076. 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);
  6077. };
  6078. /**
  6079. * 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"
  6080. * This function works in right handed mode
  6081. * @param eye defines the final position of the entity
  6082. * @param target defines where the entity should look at
  6083. * @param up defines the up vector for the entity
  6084. * @returns the new matrix
  6085. */
  6086. Matrix.LookAtRH = function (eye, target, up) {
  6087. var result = Matrix.Zero();
  6088. Matrix.LookAtRHToRef(eye, target, up, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * 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".
  6093. * This function works in right handed mode
  6094. * @param eye defines the final position of the entity
  6095. * @param target defines where the entity should look at
  6096. * @param up defines the up vector for the entity
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6100. // Z axis
  6101. eye.subtractToRef(target, this._zAxis);
  6102. this._zAxis.normalize();
  6103. // X axis
  6104. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6105. if (this._xAxis.lengthSquared() === 0) {
  6106. this._xAxis.x = 1.0;
  6107. }
  6108. else {
  6109. this._xAxis.normalize();
  6110. }
  6111. // Y axis
  6112. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6113. this._yAxis.normalize();
  6114. // Eye angles
  6115. var ex = -Vector3.Dot(this._xAxis, eye);
  6116. var ey = -Vector3.Dot(this._yAxis, eye);
  6117. var ez = -Vector3.Dot(this._zAxis, eye);
  6118. 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);
  6119. };
  6120. /**
  6121. * Create a left-handed orthographic projection matrix
  6122. * @param width defines the viewport width
  6123. * @param height defines the viewport height
  6124. * @param znear defines the near clip plane
  6125. * @param zfar defines the far clip plane
  6126. * @returns a new matrix as a left-handed orthographic projection matrix
  6127. */
  6128. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6129. var matrix = Matrix.Zero();
  6130. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6131. return matrix;
  6132. };
  6133. /**
  6134. * Store a left-handed orthographic projection to a given matrix
  6135. * @param width defines the viewport width
  6136. * @param height defines the viewport height
  6137. * @param znear defines the near clip plane
  6138. * @param zfar defines the far clip plane
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6142. var n = znear;
  6143. var f = zfar;
  6144. var a = 2.0 / width;
  6145. var b = 2.0 / height;
  6146. var c = 2.0 / (f - n);
  6147. var d = -(f + n) / (f - n);
  6148. 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);
  6149. };
  6150. /**
  6151. * Create a left-handed orthographic projection matrix
  6152. * @param left defines the viewport left coordinate
  6153. * @param right defines the viewport right coordinate
  6154. * @param bottom defines the viewport bottom coordinate
  6155. * @param top defines the viewport top coordinate
  6156. * @param znear defines the near clip plane
  6157. * @param zfar defines the far clip plane
  6158. * @returns a new matrix as a left-handed orthographic projection matrix
  6159. */
  6160. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6161. var matrix = Matrix.Zero();
  6162. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6163. return matrix;
  6164. };
  6165. /**
  6166. * Stores a left-handed orthographic projection into a given matrix
  6167. * @param left defines the viewport left coordinate
  6168. * @param right defines the viewport right coordinate
  6169. * @param bottom defines the viewport bottom coordinate
  6170. * @param top defines the viewport top coordinate
  6171. * @param znear defines the near clip plane
  6172. * @param zfar defines the far clip plane
  6173. * @param result defines the target matrix
  6174. */
  6175. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6176. var n = znear;
  6177. var f = zfar;
  6178. var a = 2.0 / (right - left);
  6179. var b = 2.0 / (top - bottom);
  6180. var c = 2.0 / (f - n);
  6181. var d = -(f + n) / (f - n);
  6182. var i0 = (left + right) / (left - right);
  6183. var i1 = (top + bottom) / (bottom - top);
  6184. 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);
  6185. };
  6186. /**
  6187. * Creates a right-handed orthographic projection matrix
  6188. * @param left defines the viewport left coordinate
  6189. * @param right defines the viewport right coordinate
  6190. * @param bottom defines the viewport bottom coordinate
  6191. * @param top defines the viewport top coordinate
  6192. * @param znear defines the near clip plane
  6193. * @param zfar defines the far clip plane
  6194. * @returns a new matrix as a right-handed orthographic projection matrix
  6195. */
  6196. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6197. var matrix = Matrix.Zero();
  6198. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6199. return matrix;
  6200. };
  6201. /**
  6202. * Stores a right-handed orthographic projection into a given matrix
  6203. * @param left defines the viewport left coordinate
  6204. * @param right defines the viewport right coordinate
  6205. * @param bottom defines the viewport bottom coordinate
  6206. * @param top defines the viewport top coordinate
  6207. * @param znear defines the near clip plane
  6208. * @param zfar defines the far clip plane
  6209. * @param result defines the target matrix
  6210. */
  6211. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6212. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6213. result.m[10] *= -1.0;
  6214. };
  6215. /**
  6216. * Creates a left-handed perspective projection matrix
  6217. * @param width defines the viewport width
  6218. * @param height defines the viewport height
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a left-handed perspective projection matrix
  6222. */
  6223. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. var n = znear;
  6226. var f = zfar;
  6227. var a = 2.0 * n / width;
  6228. var b = 2.0 * n / height;
  6229. var c = (f + n) / (f - n);
  6230. var d = -2.0 * f * n / (f - n);
  6231. 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);
  6232. return matrix;
  6233. };
  6234. /**
  6235. * Creates a left-handed perspective projection matrix
  6236. * @param fov defines the horizontal field of view
  6237. * @param aspect defines the aspect ratio
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @returns a new matrix as a left-handed perspective projection matrix
  6241. */
  6242. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6243. var matrix = Matrix.Zero();
  6244. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6245. return matrix;
  6246. };
  6247. /**
  6248. * Stores a left-handed perspective projection into a given matrix
  6249. * @param fov defines the horizontal field of view
  6250. * @param aspect defines the aspect ratio
  6251. * @param znear defines the near clip plane
  6252. * @param zfar defines the far clip plane
  6253. * @param result defines the target matrix
  6254. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6255. */
  6256. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6257. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6258. var n = znear;
  6259. var f = zfar;
  6260. var t = 1.0 / (Math.tan(fov * 0.5));
  6261. var a = isVerticalFovFixed ? (t / aspect) : t;
  6262. var b = isVerticalFovFixed ? t : (t * aspect);
  6263. var c = (f + n) / (f - n);
  6264. var d = -2.0 * f * n / (f - n);
  6265. 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);
  6266. };
  6267. /**
  6268. * Creates a right-handed perspective projection matrix
  6269. * @param fov defines the horizontal field of view
  6270. * @param aspect defines the aspect ratio
  6271. * @param znear defines the near clip plane
  6272. * @param zfar defines the far clip plane
  6273. * @returns a new matrix as a right-handed perspective projection matrix
  6274. */
  6275. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6276. var matrix = Matrix.Zero();
  6277. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6278. return matrix;
  6279. };
  6280. /**
  6281. * Stores a right-handed perspective projection into a given matrix
  6282. * @param fov defines the horizontal field of view
  6283. * @param aspect defines the aspect ratio
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6288. */
  6289. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6290. //alternatively this could be expressed as:
  6291. // m = PerspectiveFovLHToRef
  6292. // m[10] *= -1.0;
  6293. // m[11] *= -1.0;
  6294. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6295. var n = znear;
  6296. var f = zfar;
  6297. var t = 1.0 / (Math.tan(fov * 0.5));
  6298. var a = isVerticalFovFixed ? (t / aspect) : t;
  6299. var b = isVerticalFovFixed ? t : (t * aspect);
  6300. var c = -(f + n) / (f - n);
  6301. var d = -2 * f * n / (f - n);
  6302. 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);
  6303. };
  6304. /**
  6305. * Stores a perspective projection for WebVR info a given matrix
  6306. * @param fov defines the field of view
  6307. * @param znear defines the near clip plane
  6308. * @param zfar defines the far clip plane
  6309. * @param result defines the target matrix
  6310. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6311. */
  6312. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6313. if (rightHanded === void 0) { rightHanded = false; }
  6314. var rightHandedFactor = rightHanded ? -1 : 1;
  6315. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6316. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6317. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6318. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6319. var xScale = 2.0 / (leftTan + rightTan);
  6320. var yScale = 2.0 / (upTan + downTan);
  6321. result.m[0] = xScale;
  6322. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6323. result.m[5] = yScale;
  6324. result.m[6] = result.m[7] = 0.0;
  6325. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6326. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6327. result.m[10] = -zfar / (znear - zfar);
  6328. result.m[11] = 1.0 * rightHandedFactor;
  6329. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6330. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6331. result._markAsUpdated();
  6332. };
  6333. /**
  6334. * Computes a complete transformation matrix
  6335. * @param viewport defines the viewport to use
  6336. * @param world defines the world matrix
  6337. * @param view defines the view matrix
  6338. * @param projection defines the projection matrix
  6339. * @param zmin defines the near clip plane
  6340. * @param zmax defines the far clip plane
  6341. * @returns the transformation matrix
  6342. */
  6343. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6344. var cw = viewport.width;
  6345. var ch = viewport.height;
  6346. var cx = viewport.x;
  6347. var cy = viewport.y;
  6348. 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);
  6349. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6350. };
  6351. /**
  6352. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6353. * @param matrix defines the matrix to use
  6354. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6355. */
  6356. Matrix.GetAsMatrix2x2 = function (matrix) {
  6357. return new Float32Array([
  6358. matrix.m[0], matrix.m[1],
  6359. matrix.m[4], matrix.m[5]
  6360. ]);
  6361. };
  6362. /**
  6363. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6364. * @param matrix defines the matrix to use
  6365. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6366. */
  6367. Matrix.GetAsMatrix3x3 = function (matrix) {
  6368. return new Float32Array([
  6369. matrix.m[0], matrix.m[1], matrix.m[2],
  6370. matrix.m[4], matrix.m[5], matrix.m[6],
  6371. matrix.m[8], matrix.m[9], matrix.m[10]
  6372. ]);
  6373. };
  6374. /**
  6375. * Compute the transpose of a given matrix
  6376. * @param matrix defines the matrix to transpose
  6377. * @returns the new matrix
  6378. */
  6379. Matrix.Transpose = function (matrix) {
  6380. var result = new Matrix();
  6381. Matrix.TransposeToRef(matrix, result);
  6382. return result;
  6383. };
  6384. /**
  6385. * Compute the transpose of a matrix and store it in a target matrix
  6386. * @param matrix defines the matrix to transpose
  6387. * @param result defines the target matrix
  6388. */
  6389. Matrix.TransposeToRef = function (matrix, result) {
  6390. result.m[0] = matrix.m[0];
  6391. result.m[1] = matrix.m[4];
  6392. result.m[2] = matrix.m[8];
  6393. result.m[3] = matrix.m[12];
  6394. result.m[4] = matrix.m[1];
  6395. result.m[5] = matrix.m[5];
  6396. result.m[6] = matrix.m[9];
  6397. result.m[7] = matrix.m[13];
  6398. result.m[8] = matrix.m[2];
  6399. result.m[9] = matrix.m[6];
  6400. result.m[10] = matrix.m[10];
  6401. result.m[11] = matrix.m[14];
  6402. result.m[12] = matrix.m[3];
  6403. result.m[13] = matrix.m[7];
  6404. result.m[14] = matrix.m[11];
  6405. result.m[15] = matrix.m[15];
  6406. };
  6407. /**
  6408. * Computes a reflection matrix from a plane
  6409. * @param plane defines the reflection plane
  6410. * @returns a new matrix
  6411. */
  6412. Matrix.Reflection = function (plane) {
  6413. var matrix = new Matrix();
  6414. Matrix.ReflectionToRef(plane, matrix);
  6415. return matrix;
  6416. };
  6417. /**
  6418. * Computes a reflection matrix from a plane
  6419. * @param plane defines the reflection plane
  6420. * @param result defines the target matrix
  6421. */
  6422. Matrix.ReflectionToRef = function (plane, result) {
  6423. plane.normalize();
  6424. var x = plane.normal.x;
  6425. var y = plane.normal.y;
  6426. var z = plane.normal.z;
  6427. var temp = -2 * x;
  6428. var temp2 = -2 * y;
  6429. var temp3 = -2 * z;
  6430. result.m[0] = (temp * x) + 1;
  6431. result.m[1] = temp2 * x;
  6432. result.m[2] = temp3 * x;
  6433. result.m[3] = 0.0;
  6434. result.m[4] = temp * y;
  6435. result.m[5] = (temp2 * y) + 1;
  6436. result.m[6] = temp3 * y;
  6437. result.m[7] = 0.0;
  6438. result.m[8] = temp * z;
  6439. result.m[9] = temp2 * z;
  6440. result.m[10] = (temp3 * z) + 1;
  6441. result.m[11] = 0.0;
  6442. result.m[12] = temp * plane.d;
  6443. result.m[13] = temp2 * plane.d;
  6444. result.m[14] = temp3 * plane.d;
  6445. result.m[15] = 1.0;
  6446. result._markAsUpdated();
  6447. };
  6448. /**
  6449. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6450. * @param xaxis defines the value of the 1st axis
  6451. * @param yaxis defines the value of the 2nd axis
  6452. * @param zaxis defines the value of the 3rd axis
  6453. * @param result defines the target matrix
  6454. */
  6455. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6456. result.m[0] = xaxis.x;
  6457. result.m[1] = xaxis.y;
  6458. result.m[2] = xaxis.z;
  6459. result.m[3] = 0.0;
  6460. result.m[4] = yaxis.x;
  6461. result.m[5] = yaxis.y;
  6462. result.m[6] = yaxis.z;
  6463. result.m[7] = 0.0;
  6464. result.m[8] = zaxis.x;
  6465. result.m[9] = zaxis.y;
  6466. result.m[10] = zaxis.z;
  6467. result.m[11] = 0.0;
  6468. result.m[12] = 0.0;
  6469. result.m[13] = 0.0;
  6470. result.m[14] = 0.0;
  6471. result.m[15] = 1.0;
  6472. result._markAsUpdated();
  6473. };
  6474. /**
  6475. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6476. * @param quat defines the quaternion to use
  6477. * @param result defines the target matrix
  6478. */
  6479. Matrix.FromQuaternionToRef = function (quat, result) {
  6480. var xx = quat.x * quat.x;
  6481. var yy = quat.y * quat.y;
  6482. var zz = quat.z * quat.z;
  6483. var xy = quat.x * quat.y;
  6484. var zw = quat.z * quat.w;
  6485. var zx = quat.z * quat.x;
  6486. var yw = quat.y * quat.w;
  6487. var yz = quat.y * quat.z;
  6488. var xw = quat.x * quat.w;
  6489. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6490. result.m[1] = 2.0 * (xy + zw);
  6491. result.m[2] = 2.0 * (zx - yw);
  6492. result.m[3] = 0.0;
  6493. result.m[4] = 2.0 * (xy - zw);
  6494. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6495. result.m[6] = 2.0 * (yz + xw);
  6496. result.m[7] = 0.0;
  6497. result.m[8] = 2.0 * (zx + yw);
  6498. result.m[9] = 2.0 * (yz - xw);
  6499. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6500. result.m[11] = 0.0;
  6501. result.m[12] = 0.0;
  6502. result.m[13] = 0.0;
  6503. result.m[14] = 0.0;
  6504. result.m[15] = 1.0;
  6505. result._markAsUpdated();
  6506. };
  6507. Matrix._tempQuaternion = new Quaternion();
  6508. Matrix._xAxis = Vector3.Zero();
  6509. Matrix._yAxis = Vector3.Zero();
  6510. Matrix._zAxis = Vector3.Zero();
  6511. Matrix._updateFlagSeed = 0;
  6512. Matrix._identityReadOnly = Matrix.Identity();
  6513. return Matrix;
  6514. }());
  6515. BABYLON.Matrix = Matrix;
  6516. var Plane = /** @class */ (function () {
  6517. /**
  6518. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6519. */
  6520. function Plane(a, b, c, d) {
  6521. this.normal = new Vector3(a, b, c);
  6522. this.d = d;
  6523. }
  6524. /**
  6525. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6526. */
  6527. Plane.prototype.asArray = function () {
  6528. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6529. };
  6530. // Methods
  6531. /**
  6532. * Returns a new plane copied from the current Plane.
  6533. */
  6534. Plane.prototype.clone = function () {
  6535. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6536. };
  6537. /**
  6538. * Returns the string "Plane".
  6539. */
  6540. Plane.prototype.getClassName = function () {
  6541. return "Plane";
  6542. };
  6543. /**
  6544. * Returns the Plane hash code.
  6545. */
  6546. Plane.prototype.getHashCode = function () {
  6547. var hash = this.normal.getHashCode();
  6548. hash = (hash * 397) ^ (this.d || 0);
  6549. return hash;
  6550. };
  6551. /**
  6552. * Normalize the current Plane in place.
  6553. * Returns the updated Plane.
  6554. */
  6555. Plane.prototype.normalize = function () {
  6556. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6557. var magnitude = 0.0;
  6558. if (norm !== 0) {
  6559. magnitude = 1.0 / norm;
  6560. }
  6561. this.normal.x *= magnitude;
  6562. this.normal.y *= magnitude;
  6563. this.normal.z *= magnitude;
  6564. this.d *= magnitude;
  6565. return this;
  6566. };
  6567. /**
  6568. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6569. */
  6570. Plane.prototype.transform = function (transformation) {
  6571. var transposedMatrix = Matrix.Transpose(transformation);
  6572. var x = this.normal.x;
  6573. var y = this.normal.y;
  6574. var z = this.normal.z;
  6575. var d = this.d;
  6576. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6577. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6578. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6579. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6580. return new Plane(normalX, normalY, normalZ, finalD);
  6581. };
  6582. /**
  6583. * Returns the dot product (float) of the point coordinates and the plane normal.
  6584. */
  6585. Plane.prototype.dotCoordinate = function (point) {
  6586. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6587. };
  6588. /**
  6589. * Updates the current Plane from the plane defined by the three given points.
  6590. * Returns the updated Plane.
  6591. */
  6592. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6593. var x1 = point2.x - point1.x;
  6594. var y1 = point2.y - point1.y;
  6595. var z1 = point2.z - point1.z;
  6596. var x2 = point3.x - point1.x;
  6597. var y2 = point3.y - point1.y;
  6598. var z2 = point3.z - point1.z;
  6599. var yz = (y1 * z2) - (z1 * y2);
  6600. var xz = (z1 * x2) - (x1 * z2);
  6601. var xy = (x1 * y2) - (y1 * x2);
  6602. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6603. var invPyth;
  6604. if (pyth !== 0) {
  6605. invPyth = 1.0 / pyth;
  6606. }
  6607. else {
  6608. invPyth = 0.0;
  6609. }
  6610. this.normal.x = yz * invPyth;
  6611. this.normal.y = xz * invPyth;
  6612. this.normal.z = xy * invPyth;
  6613. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6614. return this;
  6615. };
  6616. /**
  6617. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6618. */
  6619. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6620. var dot = Vector3.Dot(this.normal, direction);
  6621. return (dot <= epsilon);
  6622. };
  6623. /**
  6624. * Returns the signed distance (float) from the given point to the Plane.
  6625. */
  6626. Plane.prototype.signedDistanceTo = function (point) {
  6627. return Vector3.Dot(point, this.normal) + this.d;
  6628. };
  6629. // Statics
  6630. /**
  6631. * Returns a new Plane from the given array.
  6632. */
  6633. Plane.FromArray = function (array) {
  6634. return new Plane(array[0], array[1], array[2], array[3]);
  6635. };
  6636. /**
  6637. * Returns a new Plane defined by the three given points.
  6638. */
  6639. Plane.FromPoints = function (point1, point2, point3) {
  6640. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6641. result.copyFromPoints(point1, point2, point3);
  6642. return result;
  6643. };
  6644. /**
  6645. * Returns a new Plane the normal vector to this plane at the given origin point.
  6646. * Note : the vector "normal" is updated because normalized.
  6647. */
  6648. Plane.FromPositionAndNormal = function (origin, normal) {
  6649. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6650. normal.normalize();
  6651. result.normal = normal;
  6652. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6653. return result;
  6654. };
  6655. /**
  6656. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6657. */
  6658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6660. return Vector3.Dot(point, normal) + d;
  6661. };
  6662. return Plane;
  6663. }());
  6664. BABYLON.Plane = Plane;
  6665. var Viewport = /** @class */ (function () {
  6666. /**
  6667. * Creates a Viewport object located at (x, y) and sized (width, height).
  6668. */
  6669. function Viewport(x, y, width, height) {
  6670. this.x = x;
  6671. this.y = y;
  6672. this.width = width;
  6673. this.height = height;
  6674. }
  6675. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6676. if (renderWidthOrEngine.getRenderWidth) {
  6677. var engine = renderWidthOrEngine;
  6678. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6679. }
  6680. var renderWidth = renderWidthOrEngine;
  6681. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6682. };
  6683. /**
  6684. * Returns a new Viewport copied from the current one.
  6685. */
  6686. Viewport.prototype.clone = function () {
  6687. return new Viewport(this.x, this.y, this.width, this.height);
  6688. };
  6689. return Viewport;
  6690. }());
  6691. BABYLON.Viewport = Viewport;
  6692. var Frustum = /** @class */ (function () {
  6693. function Frustum() {
  6694. }
  6695. /**
  6696. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6697. */
  6698. Frustum.GetPlanes = function (transform) {
  6699. var frustumPlanes = [];
  6700. for (var index = 0; index < 6; index++) {
  6701. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6702. }
  6703. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6704. return frustumPlanes;
  6705. };
  6706. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6707. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6708. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6709. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6710. frustumPlane.d = transform.m[15] + transform.m[14];
  6711. frustumPlane.normalize();
  6712. };
  6713. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6714. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6715. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6716. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6717. frustumPlane.d = transform.m[15] - transform.m[14];
  6718. frustumPlane.normalize();
  6719. };
  6720. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6721. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6722. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6723. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6724. frustumPlane.d = transform.m[15] + transform.m[12];
  6725. frustumPlane.normalize();
  6726. };
  6727. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6728. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6729. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6730. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6731. frustumPlane.d = transform.m[15] - transform.m[12];
  6732. frustumPlane.normalize();
  6733. };
  6734. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6735. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6736. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6737. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6738. frustumPlane.d = transform.m[15] - transform.m[13];
  6739. frustumPlane.normalize();
  6740. };
  6741. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6742. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6743. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6744. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6745. frustumPlane.d = transform.m[15] + transform.m[13];
  6746. frustumPlane.normalize();
  6747. };
  6748. /**
  6749. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6750. */
  6751. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6752. // Near
  6753. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6754. // Far
  6755. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6756. // Left
  6757. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6758. // Right
  6759. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6760. // Top
  6761. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6762. // Bottom
  6763. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6764. };
  6765. return Frustum;
  6766. }());
  6767. BABYLON.Frustum = Frustum;
  6768. /** Defines supported spaces */
  6769. var Space;
  6770. (function (Space) {
  6771. /** Local (object) space */
  6772. Space[Space["LOCAL"] = 0] = "LOCAL";
  6773. /** World space */
  6774. Space[Space["WORLD"] = 1] = "WORLD";
  6775. /** Bone space */
  6776. Space[Space["BONE"] = 2] = "BONE";
  6777. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6778. /** Defines the 3 main axes */
  6779. var Axis = /** @class */ (function () {
  6780. function Axis() {
  6781. }
  6782. /** X axis */
  6783. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6784. /** Y axis */
  6785. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6786. /** Z axis */
  6787. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6788. return Axis;
  6789. }());
  6790. BABYLON.Axis = Axis;
  6791. ;
  6792. var BezierCurve = /** @class */ (function () {
  6793. function BezierCurve() {
  6794. }
  6795. /**
  6796. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6797. */
  6798. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6799. // Extract X (which is equal to time here)
  6800. var f0 = 1 - 3 * x2 + 3 * x1;
  6801. var f1 = 3 * x2 - 6 * x1;
  6802. var f2 = 3 * x1;
  6803. var refinedT = t;
  6804. for (var i = 0; i < 5; i++) {
  6805. var refinedT2 = refinedT * refinedT;
  6806. var refinedT3 = refinedT2 * refinedT;
  6807. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6808. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6809. refinedT -= (x - t) * slope;
  6810. refinedT = Math.min(1, Math.max(0, refinedT));
  6811. }
  6812. // Resolve cubic bezier for the given x
  6813. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6814. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6815. Math.pow(refinedT, 3);
  6816. };
  6817. return BezierCurve;
  6818. }());
  6819. BABYLON.BezierCurve = BezierCurve;
  6820. /**
  6821. * Defines potential orientation for back face culling
  6822. */
  6823. var Orientation;
  6824. (function (Orientation) {
  6825. /**
  6826. * Clockwise
  6827. */
  6828. Orientation[Orientation["CW"] = 0] = "CW";
  6829. /** Counter clockwise */
  6830. Orientation[Orientation["CCW"] = 1] = "CCW";
  6831. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6832. /**
  6833. * Defines angle representation
  6834. */
  6835. var Angle = /** @class */ (function () {
  6836. /**
  6837. * Creates an Angle object of "radians" radians (float).
  6838. */
  6839. function Angle(radians) {
  6840. this._radians = radians;
  6841. if (this._radians < 0.0)
  6842. this._radians += (2.0 * Math.PI);
  6843. }
  6844. /**
  6845. * Get value in degrees
  6846. * @returns the Angle value in degrees (float)
  6847. */
  6848. Angle.prototype.degrees = function () {
  6849. return this._radians * 180.0 / Math.PI;
  6850. };
  6851. /**
  6852. * Get value in radians
  6853. * @returns the Angle value in radians (float)
  6854. */
  6855. Angle.prototype.radians = function () {
  6856. return this._radians;
  6857. };
  6858. /**
  6859. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6860. * @param a defines first vector
  6861. * @param b defines second vector
  6862. * @returns a new Angle
  6863. */
  6864. Angle.BetweenTwoPoints = function (a, b) {
  6865. var delta = b.subtract(a);
  6866. var theta = Math.atan2(delta.y, delta.x);
  6867. return new Angle(theta);
  6868. };
  6869. /**
  6870. * Gets a new Angle object from the given float in radians
  6871. * @param radians defines the angle value in radians
  6872. * @returns a new Angle
  6873. */
  6874. Angle.FromRadians = function (radians) {
  6875. return new Angle(radians);
  6876. };
  6877. /**
  6878. * Gets a new Angle object from the given float in degrees
  6879. * @param degrees defines the angle value in degrees
  6880. * @returns a new Angle
  6881. */
  6882. Angle.FromDegrees = function (degrees) {
  6883. return new Angle(degrees * Math.PI / 180.0);
  6884. };
  6885. return Angle;
  6886. }());
  6887. BABYLON.Angle = Angle;
  6888. var Arc2 = /** @class */ (function () {
  6889. /**
  6890. * Creates an Arc object from the three given points : start, middle and end.
  6891. */
  6892. function Arc2(startPoint, midPoint, endPoint) {
  6893. this.startPoint = startPoint;
  6894. this.midPoint = midPoint;
  6895. this.endPoint = endPoint;
  6896. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6897. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6898. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6899. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6900. 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);
  6901. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6902. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6903. var a1 = this.startAngle.degrees();
  6904. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6905. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6906. // angles correction
  6907. if (a2 - a1 > +180.0)
  6908. a2 -= 360.0;
  6909. if (a2 - a1 < -180.0)
  6910. a2 += 360.0;
  6911. if (a3 - a2 > +180.0)
  6912. a3 -= 360.0;
  6913. if (a3 - a2 < -180.0)
  6914. a3 += 360.0;
  6915. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6916. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6917. }
  6918. return Arc2;
  6919. }());
  6920. BABYLON.Arc2 = Arc2;
  6921. var Path2 = /** @class */ (function () {
  6922. /**
  6923. * Creates a Path2 object from the starting 2D coordinates x and y.
  6924. */
  6925. function Path2(x, y) {
  6926. this._points = new Array();
  6927. this._length = 0.0;
  6928. this.closed = false;
  6929. this._points.push(new Vector2(x, y));
  6930. }
  6931. /**
  6932. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6933. * Returns the updated Path2.
  6934. */
  6935. Path2.prototype.addLineTo = function (x, y) {
  6936. if (this.closed) {
  6937. return this;
  6938. }
  6939. var newPoint = new Vector2(x, y);
  6940. var previousPoint = this._points[this._points.length - 1];
  6941. this._points.push(newPoint);
  6942. this._length += newPoint.subtract(previousPoint).length();
  6943. return this;
  6944. };
  6945. /**
  6946. * 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.
  6947. * Returns the updated Path2.
  6948. */
  6949. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6950. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6951. if (this.closed) {
  6952. return this;
  6953. }
  6954. var startPoint = this._points[this._points.length - 1];
  6955. var midPoint = new Vector2(midX, midY);
  6956. var endPoint = new Vector2(endX, endY);
  6957. var arc = new Arc2(startPoint, midPoint, endPoint);
  6958. var increment = arc.angle.radians() / numberOfSegments;
  6959. if (arc.orientation === Orientation.CW)
  6960. increment *= -1;
  6961. var currentAngle = arc.startAngle.radians() + increment;
  6962. for (var i = 0; i < numberOfSegments; i++) {
  6963. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6964. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6965. this.addLineTo(x, y);
  6966. currentAngle += increment;
  6967. }
  6968. return this;
  6969. };
  6970. /**
  6971. * Closes the Path2.
  6972. * Returns the Path2.
  6973. */
  6974. Path2.prototype.close = function () {
  6975. this.closed = true;
  6976. return this;
  6977. };
  6978. /**
  6979. * Returns the Path2 total length (float).
  6980. */
  6981. Path2.prototype.length = function () {
  6982. var result = this._length;
  6983. if (!this.closed) {
  6984. var lastPoint = this._points[this._points.length - 1];
  6985. var firstPoint = this._points[0];
  6986. result += (firstPoint.subtract(lastPoint).length());
  6987. }
  6988. return result;
  6989. };
  6990. /**
  6991. * Returns the Path2 internal array of points.
  6992. */
  6993. Path2.prototype.getPoints = function () {
  6994. return this._points;
  6995. };
  6996. /**
  6997. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6998. */
  6999. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7000. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7001. return Vector2.Zero();
  7002. }
  7003. var lengthPosition = normalizedLengthPosition * this.length();
  7004. var previousOffset = 0;
  7005. for (var i = 0; i < this._points.length; i++) {
  7006. var j = (i + 1) % this._points.length;
  7007. var a = this._points[i];
  7008. var b = this._points[j];
  7009. var bToA = b.subtract(a);
  7010. var nextOffset = (bToA.length() + previousOffset);
  7011. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7012. var dir = bToA.normalize();
  7013. var localOffset = lengthPosition - previousOffset;
  7014. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7015. }
  7016. previousOffset = nextOffset;
  7017. }
  7018. return Vector2.Zero();
  7019. };
  7020. /**
  7021. * Returns a new Path2 starting at the coordinates (x, y).
  7022. */
  7023. Path2.StartingAt = function (x, y) {
  7024. return new Path2(x, y);
  7025. };
  7026. return Path2;
  7027. }());
  7028. BABYLON.Path2 = Path2;
  7029. var Path3D = /** @class */ (function () {
  7030. /**
  7031. * new Path3D(path, normal, raw)
  7032. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7033. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7034. * path : an array of Vector3, the curve axis of the Path3D
  7035. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7036. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7037. */
  7038. function Path3D(path, firstNormal, raw) {
  7039. if (firstNormal === void 0) { firstNormal = null; }
  7040. this.path = path;
  7041. this._curve = new Array();
  7042. this._distances = new Array();
  7043. this._tangents = new Array();
  7044. this._normals = new Array();
  7045. this._binormals = new Array();
  7046. for (var p = 0; p < path.length; p++) {
  7047. this._curve[p] = path[p].clone(); // hard copy
  7048. }
  7049. this._raw = raw || false;
  7050. this._compute(firstNormal);
  7051. }
  7052. /**
  7053. * Returns the Path3D array of successive Vector3 designing its curve.
  7054. */
  7055. Path3D.prototype.getCurve = function () {
  7056. return this._curve;
  7057. };
  7058. /**
  7059. * Returns an array populated with tangent vectors on each Path3D curve point.
  7060. */
  7061. Path3D.prototype.getTangents = function () {
  7062. return this._tangents;
  7063. };
  7064. /**
  7065. * Returns an array populated with normal vectors on each Path3D curve point.
  7066. */
  7067. Path3D.prototype.getNormals = function () {
  7068. return this._normals;
  7069. };
  7070. /**
  7071. * Returns an array populated with binormal vectors on each Path3D curve point.
  7072. */
  7073. Path3D.prototype.getBinormals = function () {
  7074. return this._binormals;
  7075. };
  7076. /**
  7077. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7078. */
  7079. Path3D.prototype.getDistances = function () {
  7080. return this._distances;
  7081. };
  7082. /**
  7083. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7084. * Returns the same object updated.
  7085. */
  7086. Path3D.prototype.update = function (path, firstNormal) {
  7087. if (firstNormal === void 0) { firstNormal = null; }
  7088. for (var p = 0; p < path.length; p++) {
  7089. this._curve[p].x = path[p].x;
  7090. this._curve[p].y = path[p].y;
  7091. this._curve[p].z = path[p].z;
  7092. }
  7093. this._compute(firstNormal);
  7094. return this;
  7095. };
  7096. // private function compute() : computes tangents, normals and binormals
  7097. Path3D.prototype._compute = function (firstNormal) {
  7098. var l = this._curve.length;
  7099. // first and last tangents
  7100. this._tangents[0] = this._getFirstNonNullVector(0);
  7101. if (!this._raw) {
  7102. this._tangents[0].normalize();
  7103. }
  7104. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7105. if (!this._raw) {
  7106. this._tangents[l - 1].normalize();
  7107. }
  7108. // normals and binormals at first point : arbitrary vector with _normalVector()
  7109. var tg0 = this._tangents[0];
  7110. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7111. this._normals[0] = pp0;
  7112. if (!this._raw) {
  7113. this._normals[0].normalize();
  7114. }
  7115. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7116. if (!this._raw) {
  7117. this._binormals[0].normalize();
  7118. }
  7119. this._distances[0] = 0.0;
  7120. // normals and binormals : next points
  7121. var prev; // previous vector (segment)
  7122. var cur; // current vector (segment)
  7123. var curTang; // current tangent
  7124. // previous normal
  7125. var prevBinor; // previous binormal
  7126. for (var i = 1; i < l; i++) {
  7127. // tangents
  7128. prev = this._getLastNonNullVector(i);
  7129. if (i < l - 1) {
  7130. cur = this._getFirstNonNullVector(i);
  7131. this._tangents[i] = prev.add(cur);
  7132. this._tangents[i].normalize();
  7133. }
  7134. this._distances[i] = this._distances[i - 1] + prev.length();
  7135. // normals and binormals
  7136. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7137. curTang = this._tangents[i];
  7138. prevBinor = this._binormals[i - 1];
  7139. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7140. if (!this._raw) {
  7141. this._normals[i].normalize();
  7142. }
  7143. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7144. if (!this._raw) {
  7145. this._binormals[i].normalize();
  7146. }
  7147. }
  7148. };
  7149. // private function getFirstNonNullVector(index)
  7150. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7151. Path3D.prototype._getFirstNonNullVector = function (index) {
  7152. var i = 1;
  7153. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7154. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7155. i++;
  7156. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7157. }
  7158. return nNVector;
  7159. };
  7160. // private function getLastNonNullVector(index)
  7161. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7162. Path3D.prototype._getLastNonNullVector = function (index) {
  7163. var i = 1;
  7164. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7165. while (nLVector.length() === 0 && index > i + 1) {
  7166. i++;
  7167. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7168. }
  7169. return nLVector;
  7170. };
  7171. // private function normalVector(v0, vt, va) :
  7172. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7173. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7174. Path3D.prototype._normalVector = function (v0, vt, va) {
  7175. var normal0;
  7176. var tgl = vt.length();
  7177. if (tgl === 0.0) {
  7178. tgl = 1.0;
  7179. }
  7180. if (va === undefined || va === null) {
  7181. var point;
  7182. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7183. point = new Vector3(0.0, -1.0, 0.0);
  7184. }
  7185. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7186. point = new Vector3(1.0, 0.0, 0.0);
  7187. }
  7188. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7189. point = new Vector3(0.0, 0.0, 1.0);
  7190. }
  7191. else {
  7192. point = Vector3.Zero();
  7193. }
  7194. normal0 = Vector3.Cross(vt, point);
  7195. }
  7196. else {
  7197. normal0 = Vector3.Cross(vt, va);
  7198. Vector3.CrossToRef(normal0, vt, normal0);
  7199. }
  7200. normal0.normalize();
  7201. return normal0;
  7202. };
  7203. return Path3D;
  7204. }());
  7205. BABYLON.Path3D = Path3D;
  7206. var Curve3 = /** @class */ (function () {
  7207. /**
  7208. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7209. * A Curve3 is designed from a series of successive Vector3.
  7210. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7211. */
  7212. function Curve3(points) {
  7213. this._length = 0.0;
  7214. this._points = points;
  7215. this._length = this._computeLength(points);
  7216. }
  7217. /**
  7218. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7219. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7220. * @param v1 (Vector3) the control point
  7221. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7222. * @param nbPoints (integer) the wanted number of points in the curve
  7223. */
  7224. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7225. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7226. var bez = new Array();
  7227. var equation = function (t, val0, val1, val2) {
  7228. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7229. return res;
  7230. };
  7231. for (var i = 0; i <= nbPoints; i++) {
  7232. 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)));
  7233. }
  7234. return new Curve3(bez);
  7235. };
  7236. /**
  7237. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7238. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7239. * @param v1 (Vector3) the first control point
  7240. * @param v2 (Vector3) the second control point
  7241. * @param v3 (Vector3) the end point of the Cubic Bezier
  7242. * @param nbPoints (integer) the wanted number of points in the curve
  7243. */
  7244. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7245. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7246. var bez = new Array();
  7247. var equation = function (t, val0, val1, val2, val3) {
  7248. 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;
  7249. return res;
  7250. };
  7251. for (var i = 0; i <= nbPoints; i++) {
  7252. 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)));
  7253. }
  7254. return new Curve3(bez);
  7255. };
  7256. /**
  7257. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7258. * @param p1 (Vector3) the origin point of the Hermite Spline
  7259. * @param t1 (Vector3) the tangent vector at the origin point
  7260. * @param p2 (Vector3) the end point of the Hermite Spline
  7261. * @param t2 (Vector3) the tangent vector at the end point
  7262. * @param nbPoints (integer) the wanted number of points in the curve
  7263. */
  7264. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7265. var hermite = new Array();
  7266. var step = 1.0 / nbPoints;
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7269. }
  7270. return new Curve3(hermite);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a CatmullRom Spline curve :
  7274. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7275. * @param nbPoints (integer) the wanted number of points between each curve control points
  7276. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7277. */
  7278. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7279. var catmullRom = new Array();
  7280. var step = 1.0 / nbPoints;
  7281. var amount = 0.0;
  7282. if (closed) {
  7283. var pointsCount = points.length;
  7284. for (var i = 0; i < pointsCount; i++) {
  7285. amount = 0;
  7286. for (var c = 0; c < nbPoints; c++) {
  7287. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7288. amount += step;
  7289. }
  7290. }
  7291. catmullRom.push(catmullRom[0]);
  7292. }
  7293. else {
  7294. var totalPoints = new Array();
  7295. totalPoints.push(points[0].clone());
  7296. Array.prototype.push.apply(totalPoints, points);
  7297. totalPoints.push(points[points.length - 1].clone());
  7298. for (var i = 0; i < totalPoints.length - 3; i++) {
  7299. amount = 0;
  7300. for (var c = 0; c < nbPoints; c++) {
  7301. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7302. amount += step;
  7303. }
  7304. }
  7305. i--;
  7306. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7307. }
  7308. return new Curve3(catmullRom);
  7309. };
  7310. /**
  7311. * Returns the Curve3 stored array of successive Vector3
  7312. */
  7313. Curve3.prototype.getPoints = function () {
  7314. return this._points;
  7315. };
  7316. /**
  7317. * Returns the computed length (float) of the curve.
  7318. */
  7319. Curve3.prototype.length = function () {
  7320. return this._length;
  7321. };
  7322. /**
  7323. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7324. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7325. * curveA and curveB keep unchanged.
  7326. */
  7327. Curve3.prototype.continue = function (curve) {
  7328. var lastPoint = this._points[this._points.length - 1];
  7329. var continuedPoints = this._points.slice();
  7330. var curvePoints = curve.getPoints();
  7331. for (var i = 1; i < curvePoints.length; i++) {
  7332. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7333. }
  7334. var continuedCurve = new Curve3(continuedPoints);
  7335. return continuedCurve;
  7336. };
  7337. Curve3.prototype._computeLength = function (path) {
  7338. var l = 0;
  7339. for (var i = 1; i < path.length; i++) {
  7340. l += (path[i].subtract(path[i - 1])).length();
  7341. }
  7342. return l;
  7343. };
  7344. return Curve3;
  7345. }());
  7346. BABYLON.Curve3 = Curve3;
  7347. // Vertex formats
  7348. var PositionNormalVertex = /** @class */ (function () {
  7349. function PositionNormalVertex(position, normal) {
  7350. if (position === void 0) { position = Vector3.Zero(); }
  7351. if (normal === void 0) { normal = Vector3.Up(); }
  7352. this.position = position;
  7353. this.normal = normal;
  7354. }
  7355. PositionNormalVertex.prototype.clone = function () {
  7356. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7357. };
  7358. return PositionNormalVertex;
  7359. }());
  7360. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7361. var PositionNormalTextureVertex = /** @class */ (function () {
  7362. function PositionNormalTextureVertex(position, normal, uv) {
  7363. if (position === void 0) { position = Vector3.Zero(); }
  7364. if (normal === void 0) { normal = Vector3.Up(); }
  7365. if (uv === void 0) { uv = Vector2.Zero(); }
  7366. this.position = position;
  7367. this.normal = normal;
  7368. this.uv = uv;
  7369. }
  7370. PositionNormalTextureVertex.prototype.clone = function () {
  7371. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7372. };
  7373. return PositionNormalTextureVertex;
  7374. }());
  7375. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7376. // Temporary pre-allocated objects for engine internal use
  7377. // usage in any internal function :
  7378. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7379. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7380. var Tmp = /** @class */ (function () {
  7381. function Tmp() {
  7382. }
  7383. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7384. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7385. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7386. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7387. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7388. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7389. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7390. Matrix.Zero(), Matrix.Zero(),
  7391. Matrix.Zero(), Matrix.Zero(),
  7392. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7393. return Tmp;
  7394. }());
  7395. BABYLON.Tmp = Tmp;
  7396. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7397. var MathTmp = /** @class */ (function () {
  7398. function MathTmp() {
  7399. }
  7400. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7401. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7402. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7403. return MathTmp;
  7404. }());
  7405. })(BABYLON || (BABYLON = {}));
  7406. //# sourceMappingURL=babylon.math.js.map
  7407. var BABYLON;
  7408. (function (BABYLON) {
  7409. var Scalar = /** @class */ (function () {
  7410. function Scalar() {
  7411. }
  7412. /**
  7413. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7414. */
  7415. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7416. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7417. var num = a - b;
  7418. return -epsilon <= num && num <= epsilon;
  7419. };
  7420. /**
  7421. * Returns a string : the upper case translation of the number i to hexadecimal.
  7422. */
  7423. Scalar.ToHex = function (i) {
  7424. var str = i.toString(16);
  7425. if (i <= 15) {
  7426. return ("0" + str).toUpperCase();
  7427. }
  7428. return str.toUpperCase();
  7429. };
  7430. /**
  7431. * Returns -1 if value is negative and +1 is value is positive.
  7432. * Returns the value itself if it's equal to zero.
  7433. */
  7434. Scalar.Sign = function (value) {
  7435. value = +value; // convert to a number
  7436. if (value === 0 || isNaN(value))
  7437. return value;
  7438. return value > 0 ? 1 : -1;
  7439. };
  7440. /**
  7441. * Returns the value itself if it's between min and max.
  7442. * Returns min if the value is lower than min.
  7443. * Returns max if the value is greater than max.
  7444. */
  7445. Scalar.Clamp = function (value, min, max) {
  7446. if (min === void 0) { min = 0; }
  7447. if (max === void 0) { max = 1; }
  7448. return Math.min(max, Math.max(min, value));
  7449. };
  7450. /**
  7451. * Returns the log2 of value.
  7452. */
  7453. Scalar.Log2 = function (value) {
  7454. return Math.log(value) * Math.LOG2E;
  7455. };
  7456. /**
  7457. * Loops the value, so that it is never larger than length and never smaller than 0.
  7458. *
  7459. * This is similar to the modulo operator but it works with floating point numbers.
  7460. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7461. * With t = 5 and length = 2.5, the result would be 0.0.
  7462. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7463. */
  7464. Scalar.Repeat = function (value, length) {
  7465. return value - Math.floor(value / length) * length;
  7466. };
  7467. /**
  7468. * Normalize the value between 0.0 and 1.0 using min and max values
  7469. */
  7470. Scalar.Normalize = function (value, min, max) {
  7471. return (value - min) / (max - min);
  7472. };
  7473. /**
  7474. * Denormalize the value from 0.0 and 1.0 using min and max values
  7475. */
  7476. Scalar.Denormalize = function (normalized, min, max) {
  7477. return (normalized * (max - min) + min);
  7478. };
  7479. /**
  7480. * Calculates the shortest difference between two given angles given in degrees.
  7481. */
  7482. Scalar.DeltaAngle = function (current, target) {
  7483. var num = Scalar.Repeat(target - current, 360.0);
  7484. if (num > 180.0) {
  7485. num -= 360.0;
  7486. }
  7487. return num;
  7488. };
  7489. /**
  7490. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7491. *
  7492. * The returned value will move back and forth between 0 and length
  7493. */
  7494. Scalar.PingPong = function (tx, length) {
  7495. var t = Scalar.Repeat(tx, length * 2.0);
  7496. return length - Math.abs(t - length);
  7497. };
  7498. /**
  7499. * Interpolates between min and max with smoothing at the limits.
  7500. *
  7501. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7502. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7503. */
  7504. Scalar.SmoothStep = function (from, to, tx) {
  7505. var t = Scalar.Clamp(tx);
  7506. t = -2.0 * t * t * t + 3.0 * t * t;
  7507. return to * t + from * (1.0 - t);
  7508. };
  7509. /**
  7510. * Moves a value current towards target.
  7511. *
  7512. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7513. * Negative values of maxDelta pushes the value away from target.
  7514. */
  7515. Scalar.MoveTowards = function (current, target, maxDelta) {
  7516. var result = 0;
  7517. if (Math.abs(target - current) <= maxDelta) {
  7518. result = target;
  7519. }
  7520. else {
  7521. result = current + Scalar.Sign(target - current) * maxDelta;
  7522. }
  7523. return result;
  7524. };
  7525. /**
  7526. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7527. *
  7528. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7529. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7530. */
  7531. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7532. var num = Scalar.DeltaAngle(current, target);
  7533. var result = 0;
  7534. if (-maxDelta < num && num < maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. target = current + num;
  7539. result = Scalar.MoveTowards(current, target, maxDelta);
  7540. }
  7541. return result;
  7542. };
  7543. /**
  7544. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7545. */
  7546. Scalar.Lerp = function (start, end, amount) {
  7547. return start + ((end - start) * amount);
  7548. };
  7549. /**
  7550. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7551. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7552. */
  7553. Scalar.LerpAngle = function (start, end, amount) {
  7554. var num = Scalar.Repeat(end - start, 360.0);
  7555. if (num > 180.0) {
  7556. num -= 360.0;
  7557. }
  7558. return start + num * Scalar.Clamp(amount);
  7559. };
  7560. /**
  7561. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7562. */
  7563. Scalar.InverseLerp = function (a, b, value) {
  7564. var result = 0;
  7565. if (a != b) {
  7566. result = Scalar.Clamp((value - a) / (b - a));
  7567. }
  7568. else {
  7569. result = 0.0;
  7570. }
  7571. return result;
  7572. };
  7573. /**
  7574. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7575. */
  7576. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7577. var squared = amount * amount;
  7578. var cubed = amount * squared;
  7579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7581. var part3 = (cubed - (2.0 * squared)) + amount;
  7582. var part4 = cubed - squared;
  7583. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7584. };
  7585. /**
  7586. * Returns a random float number between and min and max values
  7587. */
  7588. Scalar.RandomRange = function (min, max) {
  7589. if (min === max)
  7590. return min;
  7591. return ((Math.random() * (max - min)) + min);
  7592. };
  7593. /**
  7594. * This function returns percentage of a number in a given range.
  7595. *
  7596. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7597. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7598. */
  7599. Scalar.RangeToPercent = function (number, min, max) {
  7600. return ((number - min) / (max - min));
  7601. };
  7602. /**
  7603. * This function returns number that corresponds to the percentage in a given range.
  7604. *
  7605. * PercentToRange(0.34,0,100) will return 34.
  7606. */
  7607. Scalar.PercentToRange = function (percent, min, max) {
  7608. return ((max - min) * percent + min);
  7609. };
  7610. /**
  7611. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7612. * @param angle The angle to normalize in radian.
  7613. * @return The converted angle.
  7614. */
  7615. Scalar.NormalizeRadians = function (angle) {
  7616. // More precise but slower version kept for reference.
  7617. // angle = angle % Tools.TwoPi;
  7618. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7619. //if (angle > Math.PI) {
  7620. // angle -= Tools.TwoPi;
  7621. //}
  7622. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7623. return angle;
  7624. };
  7625. /**
  7626. * Two pi constants convenient for computation.
  7627. */
  7628. Scalar.TwoPi = Math.PI * 2;
  7629. return Scalar;
  7630. }());
  7631. BABYLON.Scalar = Scalar;
  7632. })(BABYLON || (BABYLON = {}));
  7633. //# sourceMappingURL=babylon.math.scalar.js.map
  7634. //# sourceMappingURL=babylon.mixins.js.map
  7635. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7636. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7637. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7638. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7639. //# sourceMappingURL=babylon.webgl2.js.map
  7640. var BABYLON;
  7641. (function (BABYLON) {
  7642. var __decoratorInitialStore = {};
  7643. var __mergedStore = {};
  7644. var _copySource = function (creationFunction, source, instanciate) {
  7645. var destination = creationFunction();
  7646. // Tags
  7647. if (BABYLON.Tags) {
  7648. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7649. }
  7650. var classStore = getMergedStore(destination);
  7651. // Properties
  7652. for (var property in classStore) {
  7653. var propertyDescriptor = classStore[property];
  7654. var sourceProperty = source[property];
  7655. var propertyType = propertyDescriptor.type;
  7656. if (sourceProperty !== undefined && sourceProperty !== null) {
  7657. switch (propertyType) {
  7658. case 0: // Value
  7659. case 6: // Mesh reference
  7660. case 11: // Camera reference
  7661. destination[property] = sourceProperty;
  7662. break;
  7663. case 1: // Texture
  7664. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7665. break;
  7666. case 2: // Color3
  7667. case 3: // FresnelParameters
  7668. case 4: // Vector2
  7669. case 5: // Vector3
  7670. case 7: // Color Curves
  7671. case 10: // Quaternion
  7672. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7673. break;
  7674. }
  7675. }
  7676. }
  7677. return destination;
  7678. };
  7679. function getDirectStore(target) {
  7680. var classKey = target.getClassName();
  7681. if (!__decoratorInitialStore[classKey]) {
  7682. __decoratorInitialStore[classKey] = {};
  7683. }
  7684. return __decoratorInitialStore[classKey];
  7685. }
  7686. /**
  7687. * Return the list of properties flagged as serializable
  7688. * @param target: host object
  7689. */
  7690. function getMergedStore(target) {
  7691. var classKey = target.getClassName();
  7692. if (__mergedStore[classKey]) {
  7693. return __mergedStore[classKey];
  7694. }
  7695. __mergedStore[classKey] = {};
  7696. var store = __mergedStore[classKey];
  7697. var currentTarget = target;
  7698. var currentKey = classKey;
  7699. while (currentKey) {
  7700. var initialStore = __decoratorInitialStore[currentKey];
  7701. for (var property in initialStore) {
  7702. store[property] = initialStore[property];
  7703. }
  7704. var parent_1 = void 0;
  7705. var done = false;
  7706. do {
  7707. parent_1 = Object.getPrototypeOf(currentTarget);
  7708. if (!parent_1.getClassName) {
  7709. done = true;
  7710. break;
  7711. }
  7712. if (parent_1.getClassName() !== currentKey) {
  7713. break;
  7714. }
  7715. currentTarget = parent_1;
  7716. } while (parent_1);
  7717. if (done) {
  7718. break;
  7719. }
  7720. currentKey = parent_1.getClassName();
  7721. currentTarget = parent_1;
  7722. }
  7723. return store;
  7724. }
  7725. function generateSerializableMember(type, sourceName) {
  7726. return function (target, propertyKey) {
  7727. var classStore = getDirectStore(target);
  7728. if (!classStore[propertyKey]) {
  7729. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7730. }
  7731. };
  7732. }
  7733. function generateExpandMember(setCallback, targetKey) {
  7734. if (targetKey === void 0) { targetKey = null; }
  7735. return function (target, propertyKey) {
  7736. var key = targetKey || ("_" + propertyKey);
  7737. Object.defineProperty(target, propertyKey, {
  7738. get: function () {
  7739. return this[key];
  7740. },
  7741. set: function (value) {
  7742. if (this[key] === value) {
  7743. return;
  7744. }
  7745. this[key] = value;
  7746. target[setCallback].apply(this);
  7747. },
  7748. enumerable: true,
  7749. configurable: true
  7750. });
  7751. };
  7752. }
  7753. function expandToProperty(callback, targetKey) {
  7754. if (targetKey === void 0) { targetKey = null; }
  7755. return generateExpandMember(callback, targetKey);
  7756. }
  7757. BABYLON.expandToProperty = expandToProperty;
  7758. function serialize(sourceName) {
  7759. return generateSerializableMember(0, sourceName); // value member
  7760. }
  7761. BABYLON.serialize = serialize;
  7762. function serializeAsTexture(sourceName) {
  7763. return generateSerializableMember(1, sourceName); // texture member
  7764. }
  7765. BABYLON.serializeAsTexture = serializeAsTexture;
  7766. function serializeAsColor3(sourceName) {
  7767. return generateSerializableMember(2, sourceName); // color3 member
  7768. }
  7769. BABYLON.serializeAsColor3 = serializeAsColor3;
  7770. function serializeAsFresnelParameters(sourceName) {
  7771. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7772. }
  7773. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7774. function serializeAsVector2(sourceName) {
  7775. return generateSerializableMember(4, sourceName); // vector2 member
  7776. }
  7777. BABYLON.serializeAsVector2 = serializeAsVector2;
  7778. function serializeAsVector3(sourceName) {
  7779. return generateSerializableMember(5, sourceName); // vector3 member
  7780. }
  7781. BABYLON.serializeAsVector3 = serializeAsVector3;
  7782. function serializeAsMeshReference(sourceName) {
  7783. return generateSerializableMember(6, sourceName); // mesh reference member
  7784. }
  7785. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7786. function serializeAsColorCurves(sourceName) {
  7787. return generateSerializableMember(7, sourceName); // color curves
  7788. }
  7789. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7790. function serializeAsColor4(sourceName) {
  7791. return generateSerializableMember(8, sourceName); // color 4
  7792. }
  7793. BABYLON.serializeAsColor4 = serializeAsColor4;
  7794. function serializeAsImageProcessingConfiguration(sourceName) {
  7795. return generateSerializableMember(9, sourceName); // image processing
  7796. }
  7797. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7798. function serializeAsQuaternion(sourceName) {
  7799. return generateSerializableMember(10, sourceName); // quaternion member
  7800. }
  7801. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7802. /**
  7803. * Decorator used to define property that can be serialized as reference to a camera
  7804. * @param sourceName defines the name of the property to decorate
  7805. */
  7806. function serializeAsCameraReference(sourceName) {
  7807. return generateSerializableMember(11, sourceName); // camera reference member
  7808. }
  7809. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7810. var SerializationHelper = /** @class */ (function () {
  7811. function SerializationHelper() {
  7812. }
  7813. SerializationHelper.Serialize = function (entity, serializationObject) {
  7814. if (!serializationObject) {
  7815. serializationObject = {};
  7816. }
  7817. // Tags
  7818. if (BABYLON.Tags) {
  7819. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7820. }
  7821. var serializedProperties = getMergedStore(entity);
  7822. // Properties
  7823. for (var property in serializedProperties) {
  7824. var propertyDescriptor = serializedProperties[property];
  7825. var targetPropertyName = propertyDescriptor.sourceName || property;
  7826. var propertyType = propertyDescriptor.type;
  7827. var sourceProperty = entity[property];
  7828. if (sourceProperty !== undefined && sourceProperty !== null) {
  7829. switch (propertyType) {
  7830. case 0: // Value
  7831. serializationObject[targetPropertyName] = sourceProperty;
  7832. break;
  7833. case 1: // Texture
  7834. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7835. break;
  7836. case 2: // Color3
  7837. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7838. break;
  7839. case 3: // FresnelParameters
  7840. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7841. break;
  7842. case 4: // Vector2
  7843. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7844. break;
  7845. case 5: // Vector3
  7846. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7847. break;
  7848. case 6: // Mesh reference
  7849. serializationObject[targetPropertyName] = sourceProperty.id;
  7850. break;
  7851. case 7: // Color Curves
  7852. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7853. break;
  7854. case 8: // Color 4
  7855. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7856. break;
  7857. case 9: // Image Processing
  7858. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7859. break;
  7860. case 10: // Quaternion
  7861. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7862. break;
  7863. case 11: // Camera reference
  7864. serializationObject[targetPropertyName] = sourceProperty.id;
  7865. break;
  7866. }
  7867. }
  7868. }
  7869. return serializationObject;
  7870. };
  7871. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7872. if (rootUrl === void 0) { rootUrl = null; }
  7873. var destination = creationFunction();
  7874. if (!rootUrl) {
  7875. rootUrl = "";
  7876. }
  7877. // Tags
  7878. if (BABYLON.Tags) {
  7879. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7880. }
  7881. var classStore = getMergedStore(destination);
  7882. // Properties
  7883. for (var property in classStore) {
  7884. var propertyDescriptor = classStore[property];
  7885. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7886. var propertyType = propertyDescriptor.type;
  7887. if (sourceProperty !== undefined && sourceProperty !== null) {
  7888. var dest = destination;
  7889. switch (propertyType) {
  7890. case 0: // Value
  7891. dest[property] = sourceProperty;
  7892. break;
  7893. case 1: // Texture
  7894. if (scene) {
  7895. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7896. }
  7897. break;
  7898. case 2: // Color3
  7899. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7900. break;
  7901. case 3: // FresnelParameters
  7902. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7903. break;
  7904. case 4: // Vector2
  7905. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7906. break;
  7907. case 5: // Vector3
  7908. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7909. break;
  7910. case 6: // Mesh reference
  7911. if (scene) {
  7912. dest[property] = scene.getLastMeshByID(sourceProperty);
  7913. }
  7914. break;
  7915. case 7: // Color Curves
  7916. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7917. break;
  7918. case 8: // Color 4
  7919. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7920. break;
  7921. case 9: // Image Processing
  7922. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7923. break;
  7924. case 10: // Quaternion
  7925. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7926. break;
  7927. case 11: // Camera reference
  7928. if (scene) {
  7929. dest[property] = scene.getCameraByID(sourceProperty);
  7930. }
  7931. break;
  7932. }
  7933. }
  7934. }
  7935. return destination;
  7936. };
  7937. SerializationHelper.Clone = function (creationFunction, source) {
  7938. return _copySource(creationFunction, source, false);
  7939. };
  7940. SerializationHelper.Instanciate = function (creationFunction, source) {
  7941. return _copySource(creationFunction, source, true);
  7942. };
  7943. return SerializationHelper;
  7944. }());
  7945. BABYLON.SerializationHelper = SerializationHelper;
  7946. })(BABYLON || (BABYLON = {}));
  7947. //# sourceMappingURL=babylon.decorators.js.map
  7948. var BABYLON;
  7949. (function (BABYLON) {
  7950. /**
  7951. * Wrapper class for promise with external resolve and reject.
  7952. */
  7953. var Deferred = /** @class */ (function () {
  7954. /**
  7955. * Constructor for this deferred object.
  7956. */
  7957. function Deferred() {
  7958. var _this = this;
  7959. this.promise = new Promise(function (resolve, reject) {
  7960. _this._resolve = resolve;
  7961. _this._reject = reject;
  7962. });
  7963. }
  7964. Object.defineProperty(Deferred.prototype, "resolve", {
  7965. /**
  7966. * The resolve method of the promise associated with this deferred object.
  7967. */
  7968. get: function () {
  7969. return this._resolve;
  7970. },
  7971. enumerable: true,
  7972. configurable: true
  7973. });
  7974. Object.defineProperty(Deferred.prototype, "reject", {
  7975. /**
  7976. * The reject method of the promise associated with this deferred object.
  7977. */
  7978. get: function () {
  7979. return this._reject;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. return Deferred;
  7985. }());
  7986. BABYLON.Deferred = Deferred;
  7987. })(BABYLON || (BABYLON = {}));
  7988. //# sourceMappingURL=babylon.deferred.js.map
  7989. var BABYLON;
  7990. (function (BABYLON) {
  7991. /**
  7992. * A class serves as a medium between the observable and its observers
  7993. */
  7994. var EventState = /** @class */ (function () {
  7995. /**
  7996. * Create a new EventState
  7997. * @param mask defines the mask associated with this state
  7998. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7999. * @param target defines the original target of the state
  8000. * @param currentTarget defines the current target of the state
  8001. */
  8002. function EventState(mask, skipNextObservers, target, currentTarget) {
  8003. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8004. this.initalize(mask, skipNextObservers, target, currentTarget);
  8005. }
  8006. /**
  8007. * Initialize the current event state
  8008. * @param mask defines the mask associated with this state
  8009. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8010. * @param target defines the original target of the state
  8011. * @param currentTarget defines the current target of the state
  8012. * @returns the current event state
  8013. */
  8014. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8015. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8016. this.mask = mask;
  8017. this.skipNextObservers = skipNextObservers;
  8018. this.target = target;
  8019. this.currentTarget = currentTarget;
  8020. return this;
  8021. };
  8022. return EventState;
  8023. }());
  8024. BABYLON.EventState = EventState;
  8025. /**
  8026. * Represent an Observer registered to a given Observable object.
  8027. */
  8028. var Observer = /** @class */ (function () {
  8029. /**
  8030. * Creates a new observer
  8031. * @param callback defines the callback to call when the observer is notified
  8032. * @param mask defines the mask of the observer (used to filter notifications)
  8033. * @param scope defines the current scope used to restore the JS context
  8034. */
  8035. function Observer(
  8036. /**
  8037. * Defines the callback to call when the observer is notified
  8038. */
  8039. callback,
  8040. /**
  8041. * Defines the mask of the observer (used to filter notifications)
  8042. */
  8043. mask,
  8044. /**
  8045. * Defines the current scope used to restore the JS context
  8046. */
  8047. scope) {
  8048. if (scope === void 0) { scope = null; }
  8049. this.callback = callback;
  8050. this.mask = mask;
  8051. this.scope = scope;
  8052. /** @hidden */
  8053. this._willBeUnregistered = false;
  8054. /**
  8055. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8056. */
  8057. this.unregisterOnNextCall = false;
  8058. }
  8059. return Observer;
  8060. }());
  8061. BABYLON.Observer = Observer;
  8062. /**
  8063. * Represent a list of observers registered to multiple Observables object.
  8064. */
  8065. var MultiObserver = /** @class */ (function () {
  8066. function MultiObserver() {
  8067. }
  8068. /**
  8069. * Release associated resources
  8070. */
  8071. MultiObserver.prototype.dispose = function () {
  8072. if (this._observers && this._observables) {
  8073. for (var index = 0; index < this._observers.length; index++) {
  8074. this._observables[index].remove(this._observers[index]);
  8075. }
  8076. }
  8077. this._observers = null;
  8078. this._observables = null;
  8079. };
  8080. /**
  8081. * Raise a callback when one of the observable will notify
  8082. * @param observables defines a list of observables to watch
  8083. * @param callback defines the callback to call on notification
  8084. * @param mask defines the mask used to filter notifications
  8085. * @param scope defines the current scope used to restore the JS context
  8086. * @returns the new MultiObserver
  8087. */
  8088. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8089. if (mask === void 0) { mask = -1; }
  8090. if (scope === void 0) { scope = null; }
  8091. var result = new MultiObserver();
  8092. result._observers = new Array();
  8093. result._observables = observables;
  8094. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8095. var observable = observables_1[_i];
  8096. var observer = observable.add(callback, mask, false, scope);
  8097. if (observer) {
  8098. result._observers.push(observer);
  8099. }
  8100. }
  8101. return result;
  8102. };
  8103. return MultiObserver;
  8104. }());
  8105. BABYLON.MultiObserver = MultiObserver;
  8106. /**
  8107. * The Observable class is a simple implementation of the Observable pattern.
  8108. *
  8109. * 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.
  8110. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8111. * 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).
  8112. * 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.
  8113. */
  8114. var Observable = /** @class */ (function () {
  8115. /**
  8116. * Creates a new observable
  8117. * @param onObserverAdded defines a callback to call when a new observer is added
  8118. */
  8119. function Observable(onObserverAdded) {
  8120. this._observers = new Array();
  8121. this._eventState = new EventState(0);
  8122. if (onObserverAdded) {
  8123. this._onObserverAdded = onObserverAdded;
  8124. }
  8125. }
  8126. /**
  8127. * Create a new Observer with the specified callback
  8128. * @param callback the callback that will be executed for that Observer
  8129. * @param mask the mask used to filter observers
  8130. * @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.
  8131. * @param scope optional scope for the callback to be called from
  8132. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8133. * @returns the new observer created for the callback
  8134. */
  8135. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8136. if (mask === void 0) { mask = -1; }
  8137. if (insertFirst === void 0) { insertFirst = false; }
  8138. if (scope === void 0) { scope = null; }
  8139. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8140. if (!callback) {
  8141. return null;
  8142. }
  8143. var observer = new Observer(callback, mask, scope);
  8144. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8145. if (insertFirst) {
  8146. this._observers.unshift(observer);
  8147. }
  8148. else {
  8149. this._observers.push(observer);
  8150. }
  8151. if (this._onObserverAdded) {
  8152. this._onObserverAdded(observer);
  8153. }
  8154. return observer;
  8155. };
  8156. /**
  8157. * Remove an Observer from the Observable object
  8158. * @param observer the instance of the Observer to remove
  8159. * @returns false if it doesn't belong to this Observable
  8160. */
  8161. Observable.prototype.remove = function (observer) {
  8162. if (!observer) {
  8163. return false;
  8164. }
  8165. var index = this._observers.indexOf(observer);
  8166. if (index !== -1) {
  8167. this._observers.splice(index, 1);
  8168. return true;
  8169. }
  8170. return false;
  8171. };
  8172. /**
  8173. * Remove a callback from the Observable object
  8174. * @param callback the callback to remove
  8175. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8176. * @returns false if it doesn't belong to this Observable
  8177. */
  8178. Observable.prototype.removeCallback = function (callback, scope) {
  8179. for (var index = 0; index < this._observers.length; index++) {
  8180. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8181. this._observers.splice(index, 1);
  8182. return true;
  8183. }
  8184. }
  8185. return false;
  8186. };
  8187. Observable.prototype._deferUnregister = function (observer) {
  8188. var _this = this;
  8189. observer.unregisterOnNextCall = false;
  8190. observer._willBeUnregistered = true;
  8191. BABYLON.Tools.SetImmediate(function () {
  8192. _this.remove(observer);
  8193. });
  8194. };
  8195. /**
  8196. * Notify all Observers by calling their respective callback with the given data
  8197. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8198. * @param eventData defines the data to send to all observers
  8199. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8200. * @param target defines the original target of the state
  8201. * @param currentTarget defines the current target of the state
  8202. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8203. */
  8204. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8205. if (mask === void 0) { mask = -1; }
  8206. if (!this._observers.length) {
  8207. return true;
  8208. }
  8209. var state = this._eventState;
  8210. state.mask = mask;
  8211. state.target = target;
  8212. state.currentTarget = currentTarget;
  8213. state.skipNextObservers = false;
  8214. state.lastReturnValue = eventData;
  8215. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8216. var obs = _a[_i];
  8217. if (obs._willBeUnregistered) {
  8218. continue;
  8219. }
  8220. if (obs.mask & mask) {
  8221. if (obs.scope) {
  8222. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8223. }
  8224. else {
  8225. state.lastReturnValue = obs.callback(eventData, state);
  8226. }
  8227. if (obs.unregisterOnNextCall) {
  8228. this._deferUnregister(obs);
  8229. }
  8230. }
  8231. if (state.skipNextObservers) {
  8232. return false;
  8233. }
  8234. }
  8235. return true;
  8236. };
  8237. /**
  8238. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8239. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8240. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8241. * and it is crucial that all callbacks will be executed.
  8242. * The order of the callbacks is kept, callbacks are not executed parallel.
  8243. *
  8244. * @param eventData The data to be sent to each callback
  8245. * @param mask is used to filter observers defaults to -1
  8246. * @param target defines the callback target (see EventState)
  8247. * @param currentTarget defines he current object in the bubbling phase
  8248. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8249. */
  8250. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8251. var _this = this;
  8252. if (mask === void 0) { mask = -1; }
  8253. // create an empty promise
  8254. var p = Promise.resolve(eventData);
  8255. // no observers? return this promise.
  8256. if (!this._observers.length) {
  8257. return p;
  8258. }
  8259. var state = this._eventState;
  8260. state.mask = mask;
  8261. state.target = target;
  8262. state.currentTarget = currentTarget;
  8263. state.skipNextObservers = false;
  8264. // execute one callback after another (not using Promise.all, the order is important)
  8265. this._observers.forEach(function (obs) {
  8266. if (state.skipNextObservers) {
  8267. return;
  8268. }
  8269. if (obs._willBeUnregistered) {
  8270. return;
  8271. }
  8272. if (obs.mask & mask) {
  8273. if (obs.scope) {
  8274. p = p.then(function (lastReturnedValue) {
  8275. state.lastReturnValue = lastReturnedValue;
  8276. return obs.callback.apply(obs.scope, [eventData, state]);
  8277. });
  8278. }
  8279. else {
  8280. p = p.then(function (lastReturnedValue) {
  8281. state.lastReturnValue = lastReturnedValue;
  8282. return obs.callback(eventData, state);
  8283. });
  8284. }
  8285. if (obs.unregisterOnNextCall) {
  8286. _this._deferUnregister(obs);
  8287. }
  8288. }
  8289. });
  8290. // return the eventData
  8291. return p.then(function () { return eventData; });
  8292. };
  8293. /**
  8294. * Notify a specific observer
  8295. * @param observer defines the observer to notify
  8296. * @param eventData defines the data to be sent to each callback
  8297. * @param mask is used to filter observers defaults to -1
  8298. */
  8299. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8300. if (mask === void 0) { mask = -1; }
  8301. var state = this._eventState;
  8302. state.mask = mask;
  8303. state.skipNextObservers = false;
  8304. observer.callback(eventData, state);
  8305. };
  8306. /**
  8307. * Gets a boolean indicating if the observable has at least one observer
  8308. * @returns true is the Observable has at least one Observer registered
  8309. */
  8310. Observable.prototype.hasObservers = function () {
  8311. return this._observers.length > 0;
  8312. };
  8313. /**
  8314. * Clear the list of observers
  8315. */
  8316. Observable.prototype.clear = function () {
  8317. this._observers = new Array();
  8318. this._onObserverAdded = null;
  8319. };
  8320. /**
  8321. * Clone the current observable
  8322. * @returns a new observable
  8323. */
  8324. Observable.prototype.clone = function () {
  8325. var result = new Observable();
  8326. result._observers = this._observers.slice(0);
  8327. return result;
  8328. };
  8329. /**
  8330. * Does this observable handles observer registered with a given mask
  8331. * @param mask defines the mask to be tested
  8332. * @return whether or not one observer registered with the given mask is handeled
  8333. **/
  8334. Observable.prototype.hasSpecificMask = function (mask) {
  8335. if (mask === void 0) { mask = -1; }
  8336. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8337. var obs = _a[_i];
  8338. if (obs.mask & mask || obs.mask === mask) {
  8339. return true;
  8340. }
  8341. }
  8342. return false;
  8343. };
  8344. return Observable;
  8345. }());
  8346. BABYLON.Observable = Observable;
  8347. })(BABYLON || (BABYLON = {}));
  8348. //# sourceMappingURL=babylon.observable.js.map
  8349. var BABYLON;
  8350. (function (BABYLON) {
  8351. var SmartArray = /** @class */ (function () {
  8352. function SmartArray(capacity) {
  8353. this.length = 0;
  8354. this.data = new Array(capacity);
  8355. this._id = SmartArray._GlobalId++;
  8356. }
  8357. SmartArray.prototype.push = function (value) {
  8358. this.data[this.length++] = value;
  8359. if (this.length > this.data.length) {
  8360. this.data.length *= 2;
  8361. }
  8362. };
  8363. SmartArray.prototype.forEach = function (func) {
  8364. for (var index = 0; index < this.length; index++) {
  8365. func(this.data[index]);
  8366. }
  8367. };
  8368. SmartArray.prototype.sort = function (compareFn) {
  8369. this.data.sort(compareFn);
  8370. };
  8371. SmartArray.prototype.reset = function () {
  8372. this.length = 0;
  8373. };
  8374. SmartArray.prototype.dispose = function () {
  8375. this.reset();
  8376. if (this.data) {
  8377. this.data.length = 0;
  8378. this.data = [];
  8379. }
  8380. };
  8381. SmartArray.prototype.concat = function (array) {
  8382. if (array.length === 0) {
  8383. return;
  8384. }
  8385. if (this.length + array.length > this.data.length) {
  8386. this.data.length = (this.length + array.length) * 2;
  8387. }
  8388. for (var index = 0; index < array.length; index++) {
  8389. this.data[this.length++] = (array.data || array)[index];
  8390. }
  8391. };
  8392. SmartArray.prototype.indexOf = function (value) {
  8393. var position = this.data.indexOf(value);
  8394. if (position >= this.length) {
  8395. return -1;
  8396. }
  8397. return position;
  8398. };
  8399. SmartArray.prototype.contains = function (value) {
  8400. return this.data.indexOf(value) !== -1;
  8401. };
  8402. // Statics
  8403. SmartArray._GlobalId = 0;
  8404. return SmartArray;
  8405. }());
  8406. BABYLON.SmartArray = SmartArray;
  8407. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8408. __extends(SmartArrayNoDuplicate, _super);
  8409. function SmartArrayNoDuplicate() {
  8410. var _this = _super !== null && _super.apply(this, arguments) || this;
  8411. _this._duplicateId = 0;
  8412. return _this;
  8413. }
  8414. SmartArrayNoDuplicate.prototype.push = function (value) {
  8415. _super.prototype.push.call(this, value);
  8416. if (!value.__smartArrayFlags) {
  8417. value.__smartArrayFlags = {};
  8418. }
  8419. value.__smartArrayFlags[this._id] = this._duplicateId;
  8420. };
  8421. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8422. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8423. return false;
  8424. }
  8425. this.push(value);
  8426. return true;
  8427. };
  8428. SmartArrayNoDuplicate.prototype.reset = function () {
  8429. _super.prototype.reset.call(this);
  8430. this._duplicateId++;
  8431. };
  8432. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8433. if (array.length === 0) {
  8434. return;
  8435. }
  8436. if (this.length + array.length > this.data.length) {
  8437. this.data.length = (this.length + array.length) * 2;
  8438. }
  8439. for (var index = 0; index < array.length; index++) {
  8440. var item = (array.data || array)[index];
  8441. this.pushNoDuplicate(item);
  8442. }
  8443. };
  8444. return SmartArrayNoDuplicate;
  8445. }(SmartArray));
  8446. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8447. })(BABYLON || (BABYLON = {}));
  8448. //# sourceMappingURL=babylon.smartArray.js.map
  8449. var BABYLON;
  8450. (function (BABYLON) {
  8451. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8452. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8453. var LoadFileError = /** @class */ (function (_super) {
  8454. __extends(LoadFileError, _super);
  8455. function LoadFileError(message, request) {
  8456. var _this = _super.call(this, message) || this;
  8457. _this.request = request;
  8458. _this.name = "LoadFileError";
  8459. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8460. return _this;
  8461. }
  8462. // Polyfill for Object.setPrototypeOf if necessary.
  8463. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8464. return LoadFileError;
  8465. }(Error));
  8466. BABYLON.LoadFileError = LoadFileError;
  8467. var RetryStrategy = /** @class */ (function () {
  8468. function RetryStrategy() {
  8469. }
  8470. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8471. if (maxRetries === void 0) { maxRetries = 3; }
  8472. if (baseInterval === void 0) { baseInterval = 500; }
  8473. return function (url, request, retryIndex) {
  8474. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8475. return -1;
  8476. }
  8477. return Math.pow(2, retryIndex) * baseInterval;
  8478. };
  8479. };
  8480. return RetryStrategy;
  8481. }());
  8482. BABYLON.RetryStrategy = RetryStrategy;
  8483. // Screenshots
  8484. var screenshotCanvas;
  8485. var cloneValue = function (source, destinationObject) {
  8486. if (!source)
  8487. return null;
  8488. if (source instanceof BABYLON.Mesh) {
  8489. return null;
  8490. }
  8491. if (source instanceof BABYLON.SubMesh) {
  8492. return source.clone(destinationObject);
  8493. }
  8494. else if (source.clone) {
  8495. return source.clone();
  8496. }
  8497. return null;
  8498. };
  8499. var Tools = /** @class */ (function () {
  8500. function Tools() {
  8501. }
  8502. /**
  8503. * Interpolates between a and b via alpha
  8504. * @param a The lower value (returned when alpha = 0)
  8505. * @param b The upper value (returned when alpha = 1)
  8506. * @param alpha The interpolation-factor
  8507. * @return The mixed value
  8508. */
  8509. Tools.Mix = function (a, b, alpha) {
  8510. return a * (1 - alpha) + b * alpha;
  8511. };
  8512. Tools.Instantiate = function (className) {
  8513. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8514. return Tools.RegisteredExternalClasses[className];
  8515. }
  8516. var arr = className.split(".");
  8517. var fn = (window || this);
  8518. for (var i = 0, len = arr.length; i < len; i++) {
  8519. fn = fn[arr[i]];
  8520. }
  8521. if (typeof fn !== "function") {
  8522. return null;
  8523. }
  8524. return fn;
  8525. };
  8526. /**
  8527. * Provides a slice function that will work even on IE
  8528. * @param data defines the array to slice
  8529. * @param start defines the start of the data (optional)
  8530. * @param end defines the end of the data (optional)
  8531. * @returns the new sliced array
  8532. */
  8533. Tools.Slice = function (data, start, end) {
  8534. if (data.slice) {
  8535. return data.slice(start, end);
  8536. }
  8537. return Array.prototype.slice.call(data, start, end);
  8538. };
  8539. Tools.SetImmediate = function (action) {
  8540. if (window.setImmediate) {
  8541. window.setImmediate(action);
  8542. }
  8543. else {
  8544. setTimeout(action, 1);
  8545. }
  8546. };
  8547. Tools.IsExponentOfTwo = function (value) {
  8548. var count = 1;
  8549. do {
  8550. count *= 2;
  8551. } while (count < value);
  8552. return count === value;
  8553. };
  8554. /**
  8555. * Returns the nearest 32-bit single precision float representation of a Number
  8556. * @param value A Number. If the parameter is of a different type, it will get converted
  8557. * to a number or to NaN if it cannot be converted
  8558. * @returns number
  8559. */
  8560. Tools.FloatRound = function (value) {
  8561. if (Math.fround) {
  8562. return Math.fround(value);
  8563. }
  8564. return (Tools._tmpFloatArray[0] = value);
  8565. };
  8566. /**
  8567. * Find the next highest power of two.
  8568. * @param x Number to start search from.
  8569. * @return Next highest power of two.
  8570. */
  8571. Tools.CeilingPOT = function (x) {
  8572. x--;
  8573. x |= x >> 1;
  8574. x |= x >> 2;
  8575. x |= x >> 4;
  8576. x |= x >> 8;
  8577. x |= x >> 16;
  8578. x++;
  8579. return x;
  8580. };
  8581. /**
  8582. * Find the next lowest power of two.
  8583. * @param x Number to start search from.
  8584. * @return Next lowest power of two.
  8585. */
  8586. Tools.FloorPOT = function (x) {
  8587. x = x | (x >> 1);
  8588. x = x | (x >> 2);
  8589. x = x | (x >> 4);
  8590. x = x | (x >> 8);
  8591. x = x | (x >> 16);
  8592. return x - (x >> 1);
  8593. };
  8594. /**
  8595. * Find the nearest power of two.
  8596. * @param x Number to start search from.
  8597. * @return Next nearest power of two.
  8598. */
  8599. Tools.NearestPOT = function (x) {
  8600. var c = Tools.CeilingPOT(x);
  8601. var f = Tools.FloorPOT(x);
  8602. return (c - x) > (x - f) ? f : c;
  8603. };
  8604. Tools.GetExponentOfTwo = function (value, max, mode) {
  8605. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8606. var pot;
  8607. switch (mode) {
  8608. case BABYLON.Engine.SCALEMODE_FLOOR:
  8609. pot = Tools.FloorPOT(value);
  8610. break;
  8611. case BABYLON.Engine.SCALEMODE_NEAREST:
  8612. pot = Tools.NearestPOT(value);
  8613. break;
  8614. case BABYLON.Engine.SCALEMODE_CEILING:
  8615. default:
  8616. pot = Tools.CeilingPOT(value);
  8617. break;
  8618. }
  8619. return Math.min(pot, max);
  8620. };
  8621. Tools.GetFilename = function (path) {
  8622. var index = path.lastIndexOf("/");
  8623. if (index < 0)
  8624. return path;
  8625. return path.substring(index + 1);
  8626. };
  8627. /**
  8628. * Extracts the "folder" part of a path (everything before the filename).
  8629. * @param uri The URI to extract the info from
  8630. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8631. * @returns The "folder" part of the path
  8632. */
  8633. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8634. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8635. var index = uri.lastIndexOf("/");
  8636. if (index < 0) {
  8637. if (returnUnchangedIfNoSlash) {
  8638. return uri;
  8639. }
  8640. return "";
  8641. }
  8642. return uri.substring(0, index + 1);
  8643. };
  8644. Tools.GetDOMTextContent = function (element) {
  8645. var result = "";
  8646. var child = element.firstChild;
  8647. while (child) {
  8648. if (child.nodeType === 3) {
  8649. result += child.textContent;
  8650. }
  8651. child = child.nextSibling;
  8652. }
  8653. return result;
  8654. };
  8655. Tools.ToDegrees = function (angle) {
  8656. return angle * 180 / Math.PI;
  8657. };
  8658. Tools.ToRadians = function (angle) {
  8659. return angle * Math.PI / 180;
  8660. };
  8661. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8662. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8663. var output = "";
  8664. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8665. var i = 0;
  8666. var bytes = new Uint8Array(buffer);
  8667. while (i < bytes.length) {
  8668. chr1 = bytes[i++];
  8669. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8670. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8671. enc1 = chr1 >> 2;
  8672. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8673. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8674. enc4 = chr3 & 63;
  8675. if (isNaN(chr2)) {
  8676. enc3 = enc4 = 64;
  8677. }
  8678. else if (isNaN(chr3)) {
  8679. enc4 = 64;
  8680. }
  8681. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8682. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8683. }
  8684. return "data:image/png;base64," + output;
  8685. };
  8686. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8687. if (bias === void 0) { bias = null; }
  8688. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8689. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8690. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8691. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8692. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8693. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8694. }
  8695. if (bias) {
  8696. minimum.x -= minimum.x * bias.x + bias.y;
  8697. minimum.y -= minimum.y * bias.x + bias.y;
  8698. minimum.z -= minimum.z * bias.x + bias.y;
  8699. maximum.x += maximum.x * bias.x + bias.y;
  8700. maximum.y += maximum.y * bias.x + bias.y;
  8701. maximum.z += maximum.z * bias.x + bias.y;
  8702. }
  8703. return {
  8704. minimum: minimum,
  8705. maximum: maximum
  8706. };
  8707. };
  8708. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8709. if (bias === void 0) { bias = null; }
  8710. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8711. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8712. if (!stride) {
  8713. stride = 3;
  8714. }
  8715. for (var index = start; index < start + count; index++) {
  8716. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8717. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8718. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8719. }
  8720. if (bias) {
  8721. minimum.x -= minimum.x * bias.x + bias.y;
  8722. minimum.y -= minimum.y * bias.x + bias.y;
  8723. minimum.z -= minimum.z * bias.x + bias.y;
  8724. maximum.x += maximum.x * bias.x + bias.y;
  8725. maximum.y += maximum.y * bias.x + bias.y;
  8726. maximum.z += maximum.z * bias.x + bias.y;
  8727. }
  8728. return {
  8729. minimum: minimum,
  8730. maximum: maximum
  8731. };
  8732. };
  8733. Tools.Vector2ArrayFeeder = function (array) {
  8734. return function (index) {
  8735. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8736. var length = isFloatArray ? array.length / 2 : array.length;
  8737. if (index >= length) {
  8738. return null;
  8739. }
  8740. if (isFloatArray) {
  8741. var fa = array;
  8742. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8743. }
  8744. var a = array;
  8745. return a[index];
  8746. };
  8747. };
  8748. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8749. if (bias === void 0) { bias = null; }
  8750. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8751. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8752. var i = 0;
  8753. var cur = feeder(i++);
  8754. while (cur) {
  8755. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8756. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8757. cur = feeder(i++);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. maximum.x += maximum.x * bias.x + bias.y;
  8763. maximum.y += maximum.y * bias.x + bias.y;
  8764. }
  8765. return {
  8766. minimum: minimum,
  8767. maximum: maximum
  8768. };
  8769. };
  8770. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8771. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8772. return null;
  8773. return Array.isArray(obj) ? obj : [obj];
  8774. };
  8775. // Misc.
  8776. Tools.GetPointerPrefix = function () {
  8777. var eventPrefix = "pointer";
  8778. // Check if pointer events are supported
  8779. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8780. eventPrefix = "mouse";
  8781. }
  8782. return eventPrefix;
  8783. };
  8784. /**
  8785. * @param func - the function to be called
  8786. * @param requester - the object that will request the next frame. Falls back to window.
  8787. */
  8788. Tools.QueueNewFrame = function (func, requester) {
  8789. if (!Tools.IsWindowObjectExist()) {
  8790. return setTimeout(func, 16);
  8791. }
  8792. if (!requester) {
  8793. requester = window;
  8794. }
  8795. if (requester.requestAnimationFrame) {
  8796. return requester.requestAnimationFrame(func);
  8797. }
  8798. else if (requester.msRequestAnimationFrame) {
  8799. return requester.msRequestAnimationFrame(func);
  8800. }
  8801. else if (requester.webkitRequestAnimationFrame) {
  8802. return requester.webkitRequestAnimationFrame(func);
  8803. }
  8804. else if (requester.mozRequestAnimationFrame) {
  8805. return requester.mozRequestAnimationFrame(func);
  8806. }
  8807. else if (requester.oRequestAnimationFrame) {
  8808. return requester.oRequestAnimationFrame(func);
  8809. }
  8810. else {
  8811. return window.setTimeout(func, 16);
  8812. }
  8813. };
  8814. Tools.RequestFullscreen = function (element) {
  8815. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8816. if (!requestFunction)
  8817. return;
  8818. requestFunction.call(element);
  8819. };
  8820. Tools.ExitFullscreen = function () {
  8821. if (document.exitFullscreen) {
  8822. document.exitFullscreen();
  8823. }
  8824. else if (document.mozCancelFullScreen) {
  8825. document.mozCancelFullScreen();
  8826. }
  8827. else if (document.webkitCancelFullScreen) {
  8828. document.webkitCancelFullScreen();
  8829. }
  8830. else if (document.msCancelFullScreen) {
  8831. document.msCancelFullScreen();
  8832. }
  8833. };
  8834. Tools.SetCorsBehavior = function (url, element) {
  8835. if (url && url.indexOf("data:") === 0) {
  8836. return;
  8837. }
  8838. if (Tools.CorsBehavior) {
  8839. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8840. element.crossOrigin = Tools.CorsBehavior;
  8841. }
  8842. else {
  8843. var result = Tools.CorsBehavior(url);
  8844. if (result) {
  8845. element.crossOrigin = result;
  8846. }
  8847. }
  8848. }
  8849. };
  8850. // External files
  8851. Tools.CleanUrl = function (url) {
  8852. url = url.replace(/#/mg, "%23");
  8853. return url;
  8854. };
  8855. Tools.LoadImage = function (url, onLoad, onError, database) {
  8856. if (url instanceof ArrayBuffer) {
  8857. url = Tools.EncodeArrayBufferTobase64(url);
  8858. }
  8859. url = Tools.CleanUrl(url);
  8860. url = Tools.PreprocessUrl(url);
  8861. var img = new Image();
  8862. Tools.SetCorsBehavior(url, img);
  8863. var loadHandler = function () {
  8864. img.removeEventListener("load", loadHandler);
  8865. img.removeEventListener("error", errorHandler);
  8866. onLoad(img);
  8867. };
  8868. var errorHandler = function (err) {
  8869. img.removeEventListener("load", loadHandler);
  8870. img.removeEventListener("error", errorHandler);
  8871. Tools.Error("Error while trying to load image: " + url);
  8872. if (onError) {
  8873. onError("Error while trying to load image: " + url, err);
  8874. }
  8875. };
  8876. img.addEventListener("load", loadHandler);
  8877. img.addEventListener("error", errorHandler);
  8878. var noIndexedDB = function () {
  8879. img.src = url;
  8880. };
  8881. var loadFromIndexedDB = function () {
  8882. if (database) {
  8883. database.loadImageFromDB(url, img);
  8884. }
  8885. };
  8886. //ANY database to do!
  8887. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8888. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8889. }
  8890. else {
  8891. if (url.indexOf("file:") !== -1) {
  8892. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8893. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8894. try {
  8895. var blobURL;
  8896. try {
  8897. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8898. }
  8899. catch (ex) {
  8900. // Chrome doesn't support oneTimeOnly parameter
  8901. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8902. }
  8903. img.src = blobURL;
  8904. }
  8905. catch (e) {
  8906. img.src = "";
  8907. }
  8908. return img;
  8909. }
  8910. }
  8911. noIndexedDB();
  8912. }
  8913. return img;
  8914. };
  8915. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8916. url = Tools.CleanUrl(url);
  8917. url = Tools.PreprocessUrl(url);
  8918. // If file and file input are set
  8919. if (url.indexOf("file:") !== -1) {
  8920. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8921. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8922. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8923. }
  8924. }
  8925. var loadUrl = Tools.BaseUrl + url;
  8926. var aborted = false;
  8927. var fileRequest = {
  8928. onCompleteObservable: new BABYLON.Observable(),
  8929. abort: function () { return aborted = true; },
  8930. };
  8931. var requestFile = function () {
  8932. var request = new XMLHttpRequest();
  8933. var retryHandle = null;
  8934. fileRequest.abort = function () {
  8935. aborted = true;
  8936. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8937. request.abort();
  8938. }
  8939. if (retryHandle !== null) {
  8940. clearTimeout(retryHandle);
  8941. retryHandle = null;
  8942. }
  8943. };
  8944. var retryLoop = function (retryIndex) {
  8945. request.open('GET', loadUrl, true);
  8946. if (useArrayBuffer) {
  8947. request.responseType = "arraybuffer";
  8948. }
  8949. if (onProgress) {
  8950. request.addEventListener("progress", onProgress);
  8951. }
  8952. var onLoadEnd = function () {
  8953. request.removeEventListener("loadend", onLoadEnd);
  8954. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8955. fileRequest.onCompleteObservable.clear();
  8956. };
  8957. request.addEventListener("loadend", onLoadEnd);
  8958. var onReadyStateChange = function () {
  8959. if (aborted) {
  8960. return;
  8961. }
  8962. // In case of undefined state in some browsers.
  8963. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8964. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8965. request.removeEventListener("readystatechange", onReadyStateChange);
  8966. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8967. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8968. return;
  8969. }
  8970. var retryStrategy = Tools.DefaultRetryStrategy;
  8971. if (retryStrategy) {
  8972. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8973. if (waitTime !== -1) {
  8974. // Prevent the request from completing for retry.
  8975. request.removeEventListener("loadend", onLoadEnd);
  8976. request = new XMLHttpRequest();
  8977. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8978. return;
  8979. }
  8980. }
  8981. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8982. if (onError) {
  8983. onError(request, e);
  8984. }
  8985. else {
  8986. throw e;
  8987. }
  8988. }
  8989. };
  8990. request.addEventListener("readystatechange", onReadyStateChange);
  8991. request.send();
  8992. };
  8993. retryLoop(0);
  8994. };
  8995. // Caching all files
  8996. if (database && database.enableSceneOffline) {
  8997. var noIndexedDB_1 = function () {
  8998. if (!aborted) {
  8999. requestFile();
  9000. }
  9001. };
  9002. var loadFromIndexedDB = function () {
  9003. // TODO: database needs to support aborting and should return a IFileRequest
  9004. if (aborted) {
  9005. return;
  9006. }
  9007. if (database) {
  9008. database.loadFileFromDB(url, function (data) {
  9009. if (!aborted) {
  9010. onSuccess(data);
  9011. }
  9012. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9013. }, onProgress ? function (event) {
  9014. if (!aborted) {
  9015. onProgress(event);
  9016. }
  9017. } : undefined, noIndexedDB_1, useArrayBuffer);
  9018. }
  9019. };
  9020. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9021. }
  9022. else {
  9023. requestFile();
  9024. }
  9025. return fileRequest;
  9026. };
  9027. /**
  9028. * Load a script (identified by an url). When the url returns, the
  9029. * content of this file is added into a new script element, attached to the DOM (body element)
  9030. */
  9031. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9032. var head = document.getElementsByTagName('head')[0];
  9033. var script = document.createElement('script');
  9034. script.type = 'text/javascript';
  9035. script.src = scriptUrl;
  9036. script.onload = function () {
  9037. if (onSuccess) {
  9038. onSuccess();
  9039. }
  9040. };
  9041. script.onerror = function (e) {
  9042. if (onError) {
  9043. onError("Unable to load script '" + scriptUrl + "'", e);
  9044. }
  9045. };
  9046. head.appendChild(script);
  9047. };
  9048. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9049. var reader = new FileReader();
  9050. var request = {
  9051. onCompleteObservable: new BABYLON.Observable(),
  9052. abort: function () { return reader.abort(); },
  9053. };
  9054. reader.onloadend = function (e) {
  9055. request.onCompleteObservable.notifyObservers(request);
  9056. };
  9057. reader.onload = function (e) {
  9058. //target doesn't have result from ts 1.3
  9059. callback(e.target['result']);
  9060. };
  9061. reader.onprogress = progressCallback;
  9062. reader.readAsDataURL(fileToLoad);
  9063. return request;
  9064. };
  9065. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9066. var reader = new FileReader();
  9067. var request = {
  9068. onCompleteObservable: new BABYLON.Observable(),
  9069. abort: function () { return reader.abort(); },
  9070. };
  9071. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9072. reader.onerror = function (e) {
  9073. Tools.Log("Error while reading file: " + fileToLoad.name);
  9074. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9075. };
  9076. reader.onload = function (e) {
  9077. //target doesn't have result from ts 1.3
  9078. callback(e.target['result']);
  9079. };
  9080. if (progressCallBack) {
  9081. reader.onprogress = progressCallBack;
  9082. }
  9083. if (!useArrayBuffer) {
  9084. // Asynchronous read
  9085. reader.readAsText(fileToLoad);
  9086. }
  9087. else {
  9088. reader.readAsArrayBuffer(fileToLoad);
  9089. }
  9090. return request;
  9091. };
  9092. //returns a downloadable url to a file content.
  9093. Tools.FileAsURL = function (content) {
  9094. var fileBlob = new Blob([content]);
  9095. var url = window.URL || window.webkitURL;
  9096. var link = url.createObjectURL(fileBlob);
  9097. return link;
  9098. };
  9099. // Misc.
  9100. Tools.Format = function (value, decimals) {
  9101. if (decimals === void 0) { decimals = 2; }
  9102. return value.toFixed(decimals);
  9103. };
  9104. Tools.CheckExtends = function (v, min, max) {
  9105. if (v.x < min.x)
  9106. min.x = v.x;
  9107. if (v.y < min.y)
  9108. min.y = v.y;
  9109. if (v.z < min.z)
  9110. min.z = v.z;
  9111. if (v.x > max.x)
  9112. max.x = v.x;
  9113. if (v.y > max.y)
  9114. max.y = v.y;
  9115. if (v.z > max.z)
  9116. max.z = v.z;
  9117. };
  9118. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9119. for (var prop in source) {
  9120. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9121. continue;
  9122. }
  9123. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9124. continue;
  9125. }
  9126. var sourceValue = source[prop];
  9127. var typeOfSourceValue = typeof sourceValue;
  9128. if (typeOfSourceValue === "function") {
  9129. continue;
  9130. }
  9131. try {
  9132. if (typeOfSourceValue === "object") {
  9133. if (sourceValue instanceof Array) {
  9134. destination[prop] = [];
  9135. if (sourceValue.length > 0) {
  9136. if (typeof sourceValue[0] == "object") {
  9137. for (var index = 0; index < sourceValue.length; index++) {
  9138. var clonedValue = cloneValue(sourceValue[index], destination);
  9139. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9140. destination[prop].push(clonedValue);
  9141. }
  9142. }
  9143. }
  9144. else {
  9145. destination[prop] = sourceValue.slice(0);
  9146. }
  9147. }
  9148. }
  9149. else {
  9150. destination[prop] = cloneValue(sourceValue, destination);
  9151. }
  9152. }
  9153. else {
  9154. destination[prop] = sourceValue;
  9155. }
  9156. }
  9157. catch (e) {
  9158. // Just ignore error (it could be because of a read-only property)
  9159. }
  9160. }
  9161. };
  9162. Tools.IsEmpty = function (obj) {
  9163. for (var i in obj) {
  9164. if (obj.hasOwnProperty(i)) {
  9165. return false;
  9166. }
  9167. }
  9168. return true;
  9169. };
  9170. Tools.RegisterTopRootEvents = function (events) {
  9171. for (var index = 0; index < events.length; index++) {
  9172. var event = events[index];
  9173. window.addEventListener(event.name, event.handler, false);
  9174. try {
  9175. if (window.parent) {
  9176. window.parent.addEventListener(event.name, event.handler, false);
  9177. }
  9178. }
  9179. catch (e) {
  9180. // Silently fails...
  9181. }
  9182. }
  9183. };
  9184. Tools.UnregisterTopRootEvents = function (events) {
  9185. for (var index = 0; index < events.length; index++) {
  9186. var event = events[index];
  9187. window.removeEventListener(event.name, event.handler);
  9188. try {
  9189. if (window.parent) {
  9190. window.parent.removeEventListener(event.name, event.handler);
  9191. }
  9192. }
  9193. catch (e) {
  9194. // Silently fails...
  9195. }
  9196. }
  9197. };
  9198. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9199. if (mimeType === void 0) { mimeType = "image/png"; }
  9200. // Read the contents of the framebuffer
  9201. var numberOfChannelsByLine = width * 4;
  9202. var halfHeight = height / 2;
  9203. //Reading datas from WebGL
  9204. var data = engine.readPixels(0, 0, width, height);
  9205. //To flip image on Y axis.
  9206. for (var i = 0; i < halfHeight; i++) {
  9207. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9208. var currentCell = j + i * numberOfChannelsByLine;
  9209. var targetLine = height - i - 1;
  9210. var targetCell = j + targetLine * numberOfChannelsByLine;
  9211. var temp = data[currentCell];
  9212. data[currentCell] = data[targetCell];
  9213. data[targetCell] = temp;
  9214. }
  9215. }
  9216. // Create a 2D canvas to store the result
  9217. if (!screenshotCanvas) {
  9218. screenshotCanvas = document.createElement('canvas');
  9219. }
  9220. screenshotCanvas.width = width;
  9221. screenshotCanvas.height = height;
  9222. var context = screenshotCanvas.getContext('2d');
  9223. if (context) {
  9224. // Copy the pixels to a 2D canvas
  9225. var imageData = context.createImageData(width, height);
  9226. var castData = (imageData.data);
  9227. castData.set(data);
  9228. context.putImageData(imageData, 0, 0);
  9229. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9230. }
  9231. };
  9232. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9233. if (mimeType === void 0) { mimeType = "image/png"; }
  9234. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9235. if (successCallback) {
  9236. successCallback(base64Image);
  9237. }
  9238. else {
  9239. // We need HTMLCanvasElement.toBlob for HD screenshots
  9240. if (!screenshotCanvas.toBlob) {
  9241. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9242. screenshotCanvas.toBlob = function (callback, type, quality) {
  9243. var _this = this;
  9244. setTimeout(function () {
  9245. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9246. for (var i = 0; i < len; i++) {
  9247. arr[i] = binStr.charCodeAt(i);
  9248. }
  9249. callback(new Blob([arr], { type: type || 'image/png' }));
  9250. });
  9251. };
  9252. }
  9253. screenshotCanvas.toBlob(function (blob) {
  9254. var url = URL.createObjectURL(blob);
  9255. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9256. if (("download" in document.createElement("a"))) {
  9257. var a = window.document.createElement("a");
  9258. a.href = url;
  9259. if (fileName) {
  9260. a.setAttribute("download", fileName);
  9261. }
  9262. else {
  9263. var date = new Date();
  9264. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9265. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9266. }
  9267. window.document.body.appendChild(a);
  9268. a.addEventListener("click", function () {
  9269. if (a.parentElement) {
  9270. a.parentElement.removeChild(a);
  9271. }
  9272. });
  9273. a.click();
  9274. }
  9275. else {
  9276. var newWindow = window.open("");
  9277. if (!newWindow)
  9278. return;
  9279. var img = newWindow.document.createElement("img");
  9280. img.onload = function () {
  9281. // no longer need to read the blob so it's revoked
  9282. URL.revokeObjectURL(url);
  9283. };
  9284. img.src = url;
  9285. newWindow.document.body.appendChild(img);
  9286. }
  9287. });
  9288. }
  9289. };
  9290. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9291. if (mimeType === void 0) { mimeType = "image/png"; }
  9292. var width;
  9293. var height;
  9294. // If a precision value is specified
  9295. if (size.precision) {
  9296. width = Math.round(engine.getRenderWidth() * size.precision);
  9297. height = Math.round(width / engine.getAspectRatio(camera));
  9298. }
  9299. else if (size.width && size.height) {
  9300. width = size.width;
  9301. height = size.height;
  9302. }
  9303. //If passing only width, computing height to keep display canvas ratio.
  9304. else if (size.width && !size.height) {
  9305. width = size.width;
  9306. height = Math.round(width / engine.getAspectRatio(camera));
  9307. }
  9308. //If passing only height, computing width to keep display canvas ratio.
  9309. else if (size.height && !size.width) {
  9310. height = size.height;
  9311. width = Math.round(height * engine.getAspectRatio(camera));
  9312. }
  9313. //Assuming here that "size" parameter is a number
  9314. else if (!isNaN(size)) {
  9315. height = size;
  9316. width = size;
  9317. }
  9318. else {
  9319. Tools.Error("Invalid 'size' parameter !");
  9320. return;
  9321. }
  9322. if (!screenshotCanvas) {
  9323. screenshotCanvas = document.createElement('canvas');
  9324. }
  9325. screenshotCanvas.width = width;
  9326. screenshotCanvas.height = height;
  9327. var renderContext = screenshotCanvas.getContext("2d");
  9328. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9329. var newWidth = width;
  9330. var newHeight = newWidth / ratio;
  9331. if (newHeight > height) {
  9332. newHeight = height;
  9333. newWidth = newHeight * ratio;
  9334. }
  9335. var offsetX = Math.max(0, width - newWidth) / 2;
  9336. var offsetY = Math.max(0, height - newHeight) / 2;
  9337. var renderingCanvas = engine.getRenderingCanvas();
  9338. if (renderContext && renderingCanvas) {
  9339. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9340. }
  9341. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9342. };
  9343. /**
  9344. * Generates an image screenshot from the specified camera.
  9345. *
  9346. * @param engine The engine to use for rendering
  9347. * @param camera The camera to use for rendering
  9348. * @param size This parameter can be set to a single number or to an object with the
  9349. * following (optional) properties: precision, width, height. If a single number is passed,
  9350. * it will be used for both width and height. If an object is passed, the screenshot size
  9351. * will be derived from the parameters. The precision property is a multiplier allowing
  9352. * rendering at a higher or lower resolution.
  9353. * @param successCallback The callback receives a single parameter which contains the
  9354. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9355. * src parameter of an <img> to display it.
  9356. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9357. * Check your browser for supported MIME types.
  9358. * @param samples Texture samples (default: 1)
  9359. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9360. * @param fileName A name for for the downloaded file.
  9361. * @constructor
  9362. */
  9363. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9364. if (mimeType === void 0) { mimeType = "image/png"; }
  9365. if (samples === void 0) { samples = 1; }
  9366. if (antialiasing === void 0) { antialiasing = false; }
  9367. var width;
  9368. var height;
  9369. //If a precision value is specified
  9370. if (size.precision) {
  9371. width = Math.round(engine.getRenderWidth() * size.precision);
  9372. height = Math.round(width / engine.getAspectRatio(camera));
  9373. size = { width: width, height: height };
  9374. }
  9375. else if (size.width && size.height) {
  9376. width = size.width;
  9377. height = size.height;
  9378. }
  9379. //If passing only width, computing height to keep display canvas ratio.
  9380. else if (size.width && !size.height) {
  9381. width = size.width;
  9382. height = Math.round(width / engine.getAspectRatio(camera));
  9383. size = { width: width, height: height };
  9384. }
  9385. //If passing only height, computing width to keep display canvas ratio.
  9386. else if (size.height && !size.width) {
  9387. height = size.height;
  9388. width = Math.round(height * engine.getAspectRatio(camera));
  9389. size = { width: width, height: height };
  9390. }
  9391. //Assuming here that "size" parameter is a number
  9392. else if (!isNaN(size)) {
  9393. height = size;
  9394. width = size;
  9395. }
  9396. else {
  9397. Tools.Error("Invalid 'size' parameter !");
  9398. return;
  9399. }
  9400. var scene = camera.getScene();
  9401. var previousCamera = null;
  9402. if (scene.activeCamera !== camera) {
  9403. previousCamera = scene.activeCamera;
  9404. scene.activeCamera = camera;
  9405. }
  9406. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9407. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9408. texture.renderList = null;
  9409. texture.samples = samples;
  9410. if (antialiasing) {
  9411. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9412. }
  9413. texture.onAfterRenderObservable.add(function () {
  9414. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9415. });
  9416. scene.incrementRenderId();
  9417. scene.resetCachedMaterial();
  9418. texture.render(true);
  9419. texture.dispose();
  9420. if (previousCamera) {
  9421. scene.activeCamera = previousCamera;
  9422. }
  9423. camera.getProjectionMatrix(true); // Force cache refresh;
  9424. };
  9425. // XHR response validator for local file scenario
  9426. Tools.ValidateXHRData = function (xhr, dataType) {
  9427. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9428. if (dataType === void 0) { dataType = 7; }
  9429. try {
  9430. if (dataType & 1) {
  9431. if (xhr.responseText && xhr.responseText.length > 0) {
  9432. return true;
  9433. }
  9434. else if (dataType === 1) {
  9435. return false;
  9436. }
  9437. }
  9438. if (dataType & 2) {
  9439. // Check header width and height since there is no "TGA" magic number
  9440. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9441. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9442. return true;
  9443. }
  9444. else if (dataType === 2) {
  9445. return false;
  9446. }
  9447. }
  9448. if (dataType & 4) {
  9449. // Check for the "DDS" magic number
  9450. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9451. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9452. return true;
  9453. }
  9454. else {
  9455. return false;
  9456. }
  9457. }
  9458. }
  9459. catch (e) {
  9460. // Global protection
  9461. }
  9462. return false;
  9463. };
  9464. /**
  9465. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9466. * Be aware Math.random() could cause collisions, but:
  9467. * "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"
  9468. */
  9469. Tools.RandomId = function () {
  9470. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9471. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9472. return v.toString(16);
  9473. });
  9474. };
  9475. /**
  9476. * Test if the given uri is a base64 string.
  9477. * @param uri The uri to test
  9478. * @return True if the uri is a base64 string or false otherwise.
  9479. */
  9480. Tools.IsBase64 = function (uri) {
  9481. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9482. };
  9483. /**
  9484. * Decode the given base64 uri.
  9485. * @param uri The uri to decode
  9486. * @return The decoded base64 data.
  9487. */
  9488. Tools.DecodeBase64 = function (uri) {
  9489. var decodedString = atob(uri.split(",")[1]);
  9490. var bufferLength = decodedString.length;
  9491. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9492. for (var i = 0; i < bufferLength; i++) {
  9493. bufferView[i] = decodedString.charCodeAt(i);
  9494. }
  9495. return bufferView.buffer;
  9496. };
  9497. Object.defineProperty(Tools, "NoneLogLevel", {
  9498. get: function () {
  9499. return Tools._NoneLogLevel;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. Object.defineProperty(Tools, "MessageLogLevel", {
  9505. get: function () {
  9506. return Tools._MessageLogLevel;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(Tools, "WarningLogLevel", {
  9512. get: function () {
  9513. return Tools._WarningLogLevel;
  9514. },
  9515. enumerable: true,
  9516. configurable: true
  9517. });
  9518. Object.defineProperty(Tools, "ErrorLogLevel", {
  9519. get: function () {
  9520. return Tools._ErrorLogLevel;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. Object.defineProperty(Tools, "AllLogLevel", {
  9526. get: function () {
  9527. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9528. },
  9529. enumerable: true,
  9530. configurable: true
  9531. });
  9532. Tools._AddLogEntry = function (entry) {
  9533. Tools._LogCache = entry + Tools._LogCache;
  9534. if (Tools.OnNewCacheEntry) {
  9535. Tools.OnNewCacheEntry(entry);
  9536. }
  9537. };
  9538. Tools._FormatMessage = function (message) {
  9539. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9540. var date = new Date();
  9541. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9542. };
  9543. Tools._LogDisabled = function (message) {
  9544. // nothing to do
  9545. };
  9546. Tools._LogEnabled = function (message) {
  9547. var formattedMessage = Tools._FormatMessage(message);
  9548. console.log("BJS - " + formattedMessage);
  9549. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9550. Tools._AddLogEntry(entry);
  9551. };
  9552. Tools._WarnDisabled = function (message) {
  9553. // nothing to do
  9554. };
  9555. Tools._WarnEnabled = function (message) {
  9556. var formattedMessage = Tools._FormatMessage(message);
  9557. console.warn("BJS - " + formattedMessage);
  9558. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9559. Tools._AddLogEntry(entry);
  9560. };
  9561. Tools._ErrorDisabled = function (message) {
  9562. // nothing to do
  9563. };
  9564. Tools._ErrorEnabled = function (message) {
  9565. Tools.errorsCount++;
  9566. var formattedMessage = Tools._FormatMessage(message);
  9567. console.error("BJS - " + formattedMessage);
  9568. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9569. Tools._AddLogEntry(entry);
  9570. };
  9571. Object.defineProperty(Tools, "LogCache", {
  9572. get: function () {
  9573. return Tools._LogCache;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Tools.ClearLogCache = function () {
  9579. Tools._LogCache = "";
  9580. Tools.errorsCount = 0;
  9581. };
  9582. Object.defineProperty(Tools, "LogLevels", {
  9583. set: function (level) {
  9584. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9585. Tools.Log = Tools._LogEnabled;
  9586. }
  9587. else {
  9588. Tools.Log = Tools._LogDisabled;
  9589. }
  9590. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9591. Tools.Warn = Tools._WarnEnabled;
  9592. }
  9593. else {
  9594. Tools.Warn = Tools._WarnDisabled;
  9595. }
  9596. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9597. Tools.Error = Tools._ErrorEnabled;
  9598. }
  9599. else {
  9600. Tools.Error = Tools._ErrorDisabled;
  9601. }
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Tools.IsWindowObjectExist = function () {
  9607. return (typeof window) !== "undefined";
  9608. };
  9609. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9610. get: function () {
  9611. return Tools._PerformanceNoneLogLevel;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9617. get: function () {
  9618. return Tools._PerformanceUserMarkLogLevel;
  9619. },
  9620. enumerable: true,
  9621. configurable: true
  9622. });
  9623. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9624. get: function () {
  9625. return Tools._PerformanceConsoleLogLevel;
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9631. set: function (level) {
  9632. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9633. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9634. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9635. return;
  9636. }
  9637. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9638. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9639. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9640. return;
  9641. }
  9642. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9643. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9644. },
  9645. enumerable: true,
  9646. configurable: true
  9647. });
  9648. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9649. };
  9650. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9651. };
  9652. Tools._StartUserMark = function (counterName, condition) {
  9653. if (condition === void 0) { condition = true; }
  9654. if (!Tools._performance) {
  9655. if (!Tools.IsWindowObjectExist()) {
  9656. return;
  9657. }
  9658. Tools._performance = window.performance;
  9659. }
  9660. if (!condition || !Tools._performance.mark) {
  9661. return;
  9662. }
  9663. Tools._performance.mark(counterName + "-Begin");
  9664. };
  9665. Tools._EndUserMark = function (counterName, condition) {
  9666. if (condition === void 0) { condition = true; }
  9667. if (!condition || !Tools._performance.mark) {
  9668. return;
  9669. }
  9670. Tools._performance.mark(counterName + "-End");
  9671. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9672. };
  9673. Tools._StartPerformanceConsole = function (counterName, condition) {
  9674. if (condition === void 0) { condition = true; }
  9675. if (!condition) {
  9676. return;
  9677. }
  9678. Tools._StartUserMark(counterName, condition);
  9679. if (console.time) {
  9680. console.time(counterName);
  9681. }
  9682. };
  9683. Tools._EndPerformanceConsole = function (counterName, condition) {
  9684. if (condition === void 0) { condition = true; }
  9685. if (!condition) {
  9686. return;
  9687. }
  9688. Tools._EndUserMark(counterName, condition);
  9689. if (console.time) {
  9690. console.timeEnd(counterName);
  9691. }
  9692. };
  9693. Object.defineProperty(Tools, "Now", {
  9694. get: function () {
  9695. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9696. return window.performance.now();
  9697. }
  9698. return Date.now();
  9699. },
  9700. enumerable: true,
  9701. configurable: true
  9702. });
  9703. /**
  9704. * This method will return the name of the class used to create the instance of the given object.
  9705. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9706. * @param object the object to get the class name from
  9707. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9708. */
  9709. Tools.GetClassName = function (object, isType) {
  9710. if (isType === void 0) { isType = false; }
  9711. var name = null;
  9712. if (!isType && object.getClassName) {
  9713. name = object.getClassName();
  9714. }
  9715. else {
  9716. if (object instanceof Object) {
  9717. var classObj = isType ? object : Object.getPrototypeOf(object);
  9718. name = classObj.constructor["__bjsclassName__"];
  9719. }
  9720. if (!name) {
  9721. name = typeof object;
  9722. }
  9723. }
  9724. return name;
  9725. };
  9726. Tools.First = function (array, predicate) {
  9727. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9728. var el = array_1[_i];
  9729. if (predicate(el)) {
  9730. return el;
  9731. }
  9732. }
  9733. return null;
  9734. };
  9735. /**
  9736. * This method will return the name of the full name of the class, including its owning module (if any).
  9737. * 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).
  9738. * @param object the object to get the class name from
  9739. * @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.
  9740. */
  9741. Tools.getFullClassName = function (object, isType) {
  9742. if (isType === void 0) { isType = false; }
  9743. var className = null;
  9744. var moduleName = null;
  9745. if (!isType && object.getClassName) {
  9746. className = object.getClassName();
  9747. }
  9748. else {
  9749. if (object instanceof Object) {
  9750. var classObj = isType ? object : Object.getPrototypeOf(object);
  9751. className = classObj.constructor["__bjsclassName__"];
  9752. moduleName = classObj.constructor["__bjsmoduleName__"];
  9753. }
  9754. if (!className) {
  9755. className = typeof object;
  9756. }
  9757. }
  9758. if (!className) {
  9759. return null;
  9760. }
  9761. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9762. };
  9763. /**
  9764. * 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.
  9765. * @param array
  9766. */
  9767. Tools.arrayOrStringFeeder = function (array) {
  9768. return function (index) {
  9769. if (index >= array.length) {
  9770. return null;
  9771. }
  9772. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9773. if (val && val.getHashCode) {
  9774. val = val.getHashCode();
  9775. }
  9776. if (typeof val === "string") {
  9777. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9778. }
  9779. return val;
  9780. };
  9781. };
  9782. /**
  9783. * Compute the hashCode of a stream of number
  9784. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9785. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9786. * @return the hash code computed
  9787. */
  9788. Tools.hashCodeFromStream = function (feeder) {
  9789. // Based from here: http://stackoverflow.com/a/7616484/802124
  9790. var hash = 0;
  9791. var index = 0;
  9792. var chr = feeder(index++);
  9793. while (chr != null) {
  9794. hash = ((hash << 5) - hash) + chr;
  9795. hash |= 0; // Convert to 32bit integer
  9796. chr = feeder(index++);
  9797. }
  9798. return hash;
  9799. };
  9800. /**
  9801. * Returns a promise that resolves after the given amount of time.
  9802. * @param delay Number of milliseconds to delay
  9803. * @returns Promise that resolves after the given amount of time
  9804. */
  9805. Tools.DelayAsync = function (delay) {
  9806. return new Promise(function (resolve) {
  9807. setTimeout(function () {
  9808. resolve();
  9809. }, delay);
  9810. });
  9811. };
  9812. Tools.BaseUrl = "";
  9813. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9814. /**
  9815. * Default behaviour for cors in the application.
  9816. * It can be a string if the expected behavior is identical in the entire app.
  9817. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9818. */
  9819. Tools.CorsBehavior = "anonymous";
  9820. Tools.UseFallbackTexture = true;
  9821. /**
  9822. * Use this object to register external classes like custom textures or material
  9823. * to allow the laoders to instantiate them
  9824. */
  9825. Tools.RegisteredExternalClasses = {};
  9826. // Used in case of a texture loading problem
  9827. 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";
  9828. Tools._tmpFloatArray = new Float32Array(1);
  9829. Tools.PreprocessUrl = function (url) {
  9830. return url;
  9831. };
  9832. // Logs
  9833. Tools._NoneLogLevel = 0;
  9834. Tools._MessageLogLevel = 1;
  9835. Tools._WarningLogLevel = 2;
  9836. Tools._ErrorLogLevel = 4;
  9837. Tools._LogCache = "";
  9838. Tools.errorsCount = 0;
  9839. Tools.Log = Tools._LogEnabled;
  9840. Tools.Warn = Tools._WarnEnabled;
  9841. Tools.Error = Tools._ErrorEnabled;
  9842. // Performances
  9843. Tools._PerformanceNoneLogLevel = 0;
  9844. Tools._PerformanceUserMarkLogLevel = 1;
  9845. Tools._PerformanceConsoleLogLevel = 2;
  9846. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9847. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9848. return Tools;
  9849. }());
  9850. BABYLON.Tools = Tools;
  9851. /**
  9852. * This class is used to track a performance counter which is number based.
  9853. * The user has access to many properties which give statistics of different nature
  9854. *
  9855. * The implementer can track two kinds of Performance Counter: time and count
  9856. * 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.
  9857. * 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.
  9858. */
  9859. var PerfCounter = /** @class */ (function () {
  9860. function PerfCounter() {
  9861. this._startMonitoringTime = 0;
  9862. this._min = 0;
  9863. this._max = 0;
  9864. this._average = 0;
  9865. this._lastSecAverage = 0;
  9866. this._current = 0;
  9867. this._totalValueCount = 0;
  9868. this._totalAccumulated = 0;
  9869. this._lastSecAccumulated = 0;
  9870. this._lastSecTime = 0;
  9871. this._lastSecValueCount = 0;
  9872. }
  9873. Object.defineProperty(PerfCounter.prototype, "min", {
  9874. /**
  9875. * Returns the smallest value ever
  9876. */
  9877. get: function () {
  9878. return this._min;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(PerfCounter.prototype, "max", {
  9884. /**
  9885. * Returns the biggest value ever
  9886. */
  9887. get: function () {
  9888. return this._max;
  9889. },
  9890. enumerable: true,
  9891. configurable: true
  9892. });
  9893. Object.defineProperty(PerfCounter.prototype, "average", {
  9894. /**
  9895. * Returns the average value since the performance counter is running
  9896. */
  9897. get: function () {
  9898. return this._average;
  9899. },
  9900. enumerable: true,
  9901. configurable: true
  9902. });
  9903. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9904. /**
  9905. * Returns the average value of the last second the counter was monitored
  9906. */
  9907. get: function () {
  9908. return this._lastSecAverage;
  9909. },
  9910. enumerable: true,
  9911. configurable: true
  9912. });
  9913. Object.defineProperty(PerfCounter.prototype, "current", {
  9914. /**
  9915. * Returns the current value
  9916. */
  9917. get: function () {
  9918. return this._current;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. Object.defineProperty(PerfCounter.prototype, "total", {
  9924. get: function () {
  9925. return this._totalAccumulated;
  9926. },
  9927. enumerable: true,
  9928. configurable: true
  9929. });
  9930. Object.defineProperty(PerfCounter.prototype, "count", {
  9931. get: function () {
  9932. return this._totalValueCount;
  9933. },
  9934. enumerable: true,
  9935. configurable: true
  9936. });
  9937. /**
  9938. * Call this method to start monitoring a new frame.
  9939. * 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.
  9940. */
  9941. PerfCounter.prototype.fetchNewFrame = function () {
  9942. this._totalValueCount++;
  9943. this._current = 0;
  9944. this._lastSecValueCount++;
  9945. };
  9946. /**
  9947. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9948. * @param newCount the count value to add to the monitored count
  9949. * @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.
  9950. */
  9951. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9952. if (!PerfCounter.Enabled) {
  9953. return;
  9954. }
  9955. this._current += newCount;
  9956. if (fetchResult) {
  9957. this._fetchResult();
  9958. }
  9959. };
  9960. /**
  9961. * Start monitoring this performance counter
  9962. */
  9963. PerfCounter.prototype.beginMonitoring = function () {
  9964. if (!PerfCounter.Enabled) {
  9965. return;
  9966. }
  9967. this._startMonitoringTime = Tools.Now;
  9968. };
  9969. /**
  9970. * Compute the time lapsed since the previous beginMonitoring() call.
  9971. * @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
  9972. */
  9973. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9974. if (newFrame === void 0) { newFrame = true; }
  9975. if (!PerfCounter.Enabled) {
  9976. return;
  9977. }
  9978. if (newFrame) {
  9979. this.fetchNewFrame();
  9980. }
  9981. var currentTime = Tools.Now;
  9982. this._current = currentTime - this._startMonitoringTime;
  9983. if (newFrame) {
  9984. this._fetchResult();
  9985. }
  9986. };
  9987. PerfCounter.prototype._fetchResult = function () {
  9988. this._totalAccumulated += this._current;
  9989. this._lastSecAccumulated += this._current;
  9990. // Min/Max update
  9991. this._min = Math.min(this._min, this._current);
  9992. this._max = Math.max(this._max, this._current);
  9993. this._average = this._totalAccumulated / this._totalValueCount;
  9994. // Reset last sec?
  9995. var now = Tools.Now;
  9996. if ((now - this._lastSecTime) > 1000) {
  9997. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9998. this._lastSecTime = now;
  9999. this._lastSecAccumulated = 0;
  10000. this._lastSecValueCount = 0;
  10001. }
  10002. };
  10003. PerfCounter.Enabled = true;
  10004. return PerfCounter;
  10005. }());
  10006. BABYLON.PerfCounter = PerfCounter;
  10007. /**
  10008. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10009. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10010. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10011. * @param name The name of the class, case should be preserved
  10012. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10013. */
  10014. function className(name, module) {
  10015. return function (target) {
  10016. target["__bjsclassName__"] = name;
  10017. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10018. };
  10019. }
  10020. BABYLON.className = className;
  10021. /**
  10022. * An implementation of a loop for asynchronous functions.
  10023. */
  10024. var AsyncLoop = /** @class */ (function () {
  10025. /**
  10026. * Constroctor.
  10027. * @param iterations the number of iterations.
  10028. * @param _fn the function to run each iteration
  10029. * @param _successCallback the callback that will be called upon succesful execution
  10030. * @param offset starting offset.
  10031. */
  10032. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10033. if (offset === void 0) { offset = 0; }
  10034. this.iterations = iterations;
  10035. this._fn = _fn;
  10036. this._successCallback = _successCallback;
  10037. this.index = offset - 1;
  10038. this._done = false;
  10039. }
  10040. /**
  10041. * Execute the next iteration. Must be called after the last iteration was finished.
  10042. */
  10043. AsyncLoop.prototype.executeNext = function () {
  10044. if (!this._done) {
  10045. if (this.index + 1 < this.iterations) {
  10046. ++this.index;
  10047. this._fn(this);
  10048. }
  10049. else {
  10050. this.breakLoop();
  10051. }
  10052. }
  10053. };
  10054. /**
  10055. * Break the loop and run the success callback.
  10056. */
  10057. AsyncLoop.prototype.breakLoop = function () {
  10058. this._done = true;
  10059. this._successCallback();
  10060. };
  10061. /**
  10062. * Helper function
  10063. */
  10064. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10065. if (offset === void 0) { offset = 0; }
  10066. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10067. loop.executeNext();
  10068. return loop;
  10069. };
  10070. /**
  10071. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10072. * @param iterations total number of iterations
  10073. * @param syncedIterations number of synchronous iterations in each async iteration.
  10074. * @param fn the function to call each iteration.
  10075. * @param callback a success call back that will be called when iterating stops.
  10076. * @param breakFunction a break condition (optional)
  10077. * @param timeout timeout settings for the setTimeout function. default - 0.
  10078. * @constructor
  10079. */
  10080. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10081. if (timeout === void 0) { timeout = 0; }
  10082. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10083. if (breakFunction && breakFunction())
  10084. loop.breakLoop();
  10085. else {
  10086. setTimeout(function () {
  10087. for (var i = 0; i < syncedIterations; ++i) {
  10088. var iteration = (loop.index * syncedIterations) + i;
  10089. if (iteration >= iterations)
  10090. break;
  10091. fn(iteration);
  10092. if (breakFunction && breakFunction()) {
  10093. loop.breakLoop();
  10094. break;
  10095. }
  10096. }
  10097. loop.executeNext();
  10098. }, timeout);
  10099. }
  10100. }, callback);
  10101. };
  10102. return AsyncLoop;
  10103. }());
  10104. BABYLON.AsyncLoop = AsyncLoop;
  10105. })(BABYLON || (BABYLON = {}));
  10106. //# sourceMappingURL=babylon.tools.js.map
  10107. var BABYLON;
  10108. (function (BABYLON) {
  10109. var PromiseStates;
  10110. (function (PromiseStates) {
  10111. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10112. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10113. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10114. })(PromiseStates || (PromiseStates = {}));
  10115. var FulFillmentAgregator = /** @class */ (function () {
  10116. function FulFillmentAgregator() {
  10117. this.count = 0;
  10118. this.target = 0;
  10119. this.results = [];
  10120. }
  10121. return FulFillmentAgregator;
  10122. }());
  10123. var InternalPromise = /** @class */ (function () {
  10124. function InternalPromise(resolver) {
  10125. var _this = this;
  10126. this._state = PromiseStates.Pending;
  10127. this._children = new Array();
  10128. this._rejectWasConsumed = false;
  10129. if (!resolver) {
  10130. return;
  10131. }
  10132. try {
  10133. resolver(function (value) {
  10134. _this._resolve(value);
  10135. }, function (reason) {
  10136. _this._reject(reason);
  10137. });
  10138. }
  10139. catch (e) {
  10140. this._reject(e);
  10141. }
  10142. }
  10143. Object.defineProperty(InternalPromise.prototype, "_result", {
  10144. get: function () {
  10145. return this._resultValue;
  10146. },
  10147. set: function (value) {
  10148. this._resultValue = value;
  10149. if (this._parent && this._parent._result === undefined) {
  10150. this._parent._result = value;
  10151. }
  10152. },
  10153. enumerable: true,
  10154. configurable: true
  10155. });
  10156. InternalPromise.prototype.catch = function (onRejected) {
  10157. return this.then(undefined, onRejected);
  10158. };
  10159. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10160. var _this = this;
  10161. var newPromise = new InternalPromise();
  10162. newPromise._onFulfilled = onFulfilled;
  10163. newPromise._onRejected = onRejected;
  10164. // Composition
  10165. this._children.push(newPromise);
  10166. newPromise._parent = this;
  10167. if (this._state !== PromiseStates.Pending) {
  10168. BABYLON.Tools.SetImmediate(function () {
  10169. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10170. var returnedValue = newPromise._resolve(_this._result);
  10171. if (returnedValue !== undefined && returnedValue !== null) {
  10172. if (returnedValue._state !== undefined) {
  10173. var returnedPromise = returnedValue;
  10174. newPromise._children.push(returnedPromise);
  10175. returnedPromise._parent = newPromise;
  10176. newPromise = returnedPromise;
  10177. }
  10178. else {
  10179. newPromise._result = returnedValue;
  10180. }
  10181. }
  10182. }
  10183. else {
  10184. newPromise._reject(_this._reason);
  10185. }
  10186. });
  10187. }
  10188. return newPromise;
  10189. };
  10190. InternalPromise.prototype._moveChildren = function (children) {
  10191. var _this = this;
  10192. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10193. this._children.forEach(function (child) {
  10194. child._parent = _this;
  10195. });
  10196. if (this._state === PromiseStates.Fulfilled) {
  10197. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10198. var child = _b[_i];
  10199. child._resolve(this._result);
  10200. }
  10201. }
  10202. else if (this._state === PromiseStates.Rejected) {
  10203. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10204. var child = _d[_c];
  10205. child._reject(this._reason);
  10206. }
  10207. }
  10208. var _a;
  10209. };
  10210. InternalPromise.prototype._resolve = function (value) {
  10211. try {
  10212. this._state = PromiseStates.Fulfilled;
  10213. var returnedValue = null;
  10214. if (this._onFulfilled) {
  10215. returnedValue = this._onFulfilled(value);
  10216. }
  10217. if (returnedValue !== undefined && returnedValue !== null) {
  10218. if (returnedValue._state !== undefined) {
  10219. // Transmit children
  10220. var returnedPromise = returnedValue;
  10221. returnedPromise._parent = this;
  10222. returnedPromise._moveChildren(this._children);
  10223. value = returnedPromise._result;
  10224. }
  10225. else {
  10226. value = returnedValue;
  10227. }
  10228. }
  10229. this._result = value;
  10230. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10231. var child = _a[_i];
  10232. child._resolve(value);
  10233. }
  10234. this._children.length = 0;
  10235. delete this._onFulfilled;
  10236. delete this._onRejected;
  10237. }
  10238. catch (e) {
  10239. this._reject(e, true);
  10240. }
  10241. };
  10242. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10243. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10244. this._state = PromiseStates.Rejected;
  10245. this._reason = reason;
  10246. if (this._onRejected && !onLocalThrow) {
  10247. try {
  10248. this._onRejected(reason);
  10249. this._rejectWasConsumed = true;
  10250. }
  10251. catch (e) {
  10252. reason = e;
  10253. }
  10254. }
  10255. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10256. var child = _a[_i];
  10257. if (this._rejectWasConsumed) {
  10258. child._resolve(null);
  10259. }
  10260. else {
  10261. child._reject(reason);
  10262. }
  10263. }
  10264. this._children.length = 0;
  10265. delete this._onFulfilled;
  10266. delete this._onRejected;
  10267. };
  10268. InternalPromise.resolve = function (value) {
  10269. var newPromise = new InternalPromise();
  10270. newPromise._resolve(value);
  10271. return newPromise;
  10272. };
  10273. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10274. promise.then(function (value) {
  10275. agregator.results[index] = value;
  10276. agregator.count++;
  10277. if (agregator.count === agregator.target) {
  10278. agregator.rootPromise._resolve(agregator.results);
  10279. }
  10280. return null;
  10281. }, function (reason) {
  10282. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10283. agregator.rootPromise._reject(reason);
  10284. }
  10285. });
  10286. };
  10287. InternalPromise.all = function (promises) {
  10288. var newPromise = new InternalPromise();
  10289. var agregator = new FulFillmentAgregator();
  10290. agregator.target = promises.length;
  10291. agregator.rootPromise = newPromise;
  10292. if (promises.length) {
  10293. for (var index = 0; index < promises.length; index++) {
  10294. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10295. }
  10296. }
  10297. else {
  10298. newPromise._resolve([]);
  10299. }
  10300. return newPromise;
  10301. };
  10302. InternalPromise.race = function (promises) {
  10303. var newPromise = new InternalPromise();
  10304. if (promises.length) {
  10305. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10306. var promise = promises_1[_i];
  10307. promise.then(function (value) {
  10308. if (newPromise) {
  10309. newPromise._resolve(value);
  10310. newPromise = null;
  10311. }
  10312. return null;
  10313. }, function (reason) {
  10314. if (newPromise) {
  10315. newPromise._reject(reason);
  10316. newPromise = null;
  10317. }
  10318. });
  10319. }
  10320. }
  10321. return newPromise;
  10322. };
  10323. return InternalPromise;
  10324. }());
  10325. /**
  10326. * Helper class that provides a small promise polyfill
  10327. */
  10328. var PromisePolyfill = /** @class */ (function () {
  10329. function PromisePolyfill() {
  10330. }
  10331. /**
  10332. * Static function used to check if the polyfill is required
  10333. * If this is the case then the function will inject the polyfill to window.Promise
  10334. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10335. */
  10336. PromisePolyfill.Apply = function (force) {
  10337. if (force === void 0) { force = false; }
  10338. if (force || typeof Promise === 'undefined') {
  10339. var root = window;
  10340. root.Promise = InternalPromise;
  10341. }
  10342. };
  10343. return PromisePolyfill;
  10344. }());
  10345. BABYLON.PromisePolyfill = PromisePolyfill;
  10346. })(BABYLON || (BABYLON = {}));
  10347. //# sourceMappingURL=babylon.promise.js.map
  10348. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10349. var BABYLON;
  10350. (function (BABYLON) {
  10351. /**
  10352. * Helper class to push actions to a pool of workers.
  10353. */
  10354. var WorkerPool = /** @class */ (function () {
  10355. /**
  10356. * Constructor
  10357. * @param workers Array of workers to use for actions
  10358. */
  10359. function WorkerPool(workers) {
  10360. this._pendingActions = new Array();
  10361. this._workerInfos = workers.map(function (worker) { return ({
  10362. worker: worker,
  10363. active: false
  10364. }); });
  10365. }
  10366. /**
  10367. * Terminates all workers and clears any pending actions.
  10368. */
  10369. WorkerPool.prototype.dispose = function () {
  10370. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10371. var workerInfo = _a[_i];
  10372. workerInfo.worker.terminate();
  10373. }
  10374. delete this._workerInfos;
  10375. delete this._pendingActions;
  10376. };
  10377. /**
  10378. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10379. * pended until a worker has completed its action.
  10380. * @param action The action to perform. Call onComplete when the action is complete.
  10381. */
  10382. WorkerPool.prototype.push = function (action) {
  10383. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10384. var workerInfo = _a[_i];
  10385. if (!workerInfo.active) {
  10386. this._execute(workerInfo, action);
  10387. return;
  10388. }
  10389. }
  10390. this._pendingActions.push(action);
  10391. };
  10392. WorkerPool.prototype._execute = function (workerInfo, action) {
  10393. var _this = this;
  10394. workerInfo.active = true;
  10395. action(workerInfo.worker, function () {
  10396. workerInfo.active = false;
  10397. var nextAction = _this._pendingActions.shift();
  10398. if (nextAction) {
  10399. _this._execute(workerInfo, nextAction);
  10400. }
  10401. });
  10402. };
  10403. return WorkerPool;
  10404. }());
  10405. BABYLON.WorkerPool = WorkerPool;
  10406. })(BABYLON || (BABYLON = {}));
  10407. //# sourceMappingURL=babylon.workerPool.js.map
  10408. var BABYLON;
  10409. (function (BABYLON) {
  10410. /**
  10411. * @hidden
  10412. **/
  10413. var _AlphaState = /** @class */ (function () {
  10414. /**
  10415. * Initializes the state.
  10416. */
  10417. function _AlphaState() {
  10418. this._isAlphaBlendDirty = false;
  10419. this._isBlendFunctionParametersDirty = false;
  10420. this._isBlendEquationParametersDirty = false;
  10421. this._isBlendConstantsDirty = false;
  10422. this._alphaBlend = false;
  10423. this._blendFunctionParameters = new Array(4);
  10424. this._blendEquationParameters = new Array(2);
  10425. this._blendConstants = new Array(4);
  10426. this.reset();
  10427. }
  10428. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10429. get: function () {
  10430. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10436. get: function () {
  10437. return this._alphaBlend;
  10438. },
  10439. set: function (value) {
  10440. if (this._alphaBlend === value) {
  10441. return;
  10442. }
  10443. this._alphaBlend = value;
  10444. this._isAlphaBlendDirty = true;
  10445. },
  10446. enumerable: true,
  10447. configurable: true
  10448. });
  10449. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10450. if (this._blendConstants[0] === r &&
  10451. this._blendConstants[1] === g &&
  10452. this._blendConstants[2] === b &&
  10453. this._blendConstants[3] === a) {
  10454. return;
  10455. }
  10456. this._blendConstants[0] = r;
  10457. this._blendConstants[1] = g;
  10458. this._blendConstants[2] = b;
  10459. this._blendConstants[3] = a;
  10460. this._isBlendConstantsDirty = true;
  10461. };
  10462. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10463. if (this._blendFunctionParameters[0] === value0 &&
  10464. this._blendFunctionParameters[1] === value1 &&
  10465. this._blendFunctionParameters[2] === value2 &&
  10466. this._blendFunctionParameters[3] === value3) {
  10467. return;
  10468. }
  10469. this._blendFunctionParameters[0] = value0;
  10470. this._blendFunctionParameters[1] = value1;
  10471. this._blendFunctionParameters[2] = value2;
  10472. this._blendFunctionParameters[3] = value3;
  10473. this._isBlendFunctionParametersDirty = true;
  10474. };
  10475. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10476. if (this._blendEquationParameters[0] === rgb &&
  10477. this._blendEquationParameters[1] === alpha) {
  10478. return;
  10479. }
  10480. this._blendEquationParameters[0] = rgb;
  10481. this._blendEquationParameters[1] = alpha;
  10482. this._isBlendEquationParametersDirty = true;
  10483. };
  10484. _AlphaState.prototype.reset = function () {
  10485. this._alphaBlend = false;
  10486. this._blendFunctionParameters[0] = null;
  10487. this._blendFunctionParameters[1] = null;
  10488. this._blendFunctionParameters[2] = null;
  10489. this._blendFunctionParameters[3] = null;
  10490. this._blendEquationParameters[0] = null;
  10491. this._blendEquationParameters[1] = null;
  10492. this._blendConstants[0] = null;
  10493. this._blendConstants[1] = null;
  10494. this._blendConstants[2] = null;
  10495. this._blendConstants[3] = null;
  10496. this._isAlphaBlendDirty = true;
  10497. this._isBlendFunctionParametersDirty = false;
  10498. this._isBlendEquationParametersDirty = false;
  10499. this._isBlendConstantsDirty = false;
  10500. };
  10501. _AlphaState.prototype.apply = function (gl) {
  10502. if (!this.isDirty) {
  10503. return;
  10504. }
  10505. // Alpha blend
  10506. if (this._isAlphaBlendDirty) {
  10507. if (this._alphaBlend) {
  10508. gl.enable(gl.BLEND);
  10509. }
  10510. else {
  10511. gl.disable(gl.BLEND);
  10512. }
  10513. this._isAlphaBlendDirty = false;
  10514. }
  10515. // Alpha function
  10516. if (this._isBlendFunctionParametersDirty) {
  10517. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10518. this._isBlendFunctionParametersDirty = false;
  10519. }
  10520. // Alpha equation
  10521. if (this._isBlendEquationParametersDirty) {
  10522. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10523. this._isBlendEquationParametersDirty = false;
  10524. }
  10525. // Constants
  10526. if (this._isBlendConstantsDirty) {
  10527. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10528. this._isBlendConstantsDirty = false;
  10529. }
  10530. };
  10531. return _AlphaState;
  10532. }());
  10533. BABYLON._AlphaState = _AlphaState;
  10534. })(BABYLON || (BABYLON = {}));
  10535. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10536. var BABYLON;
  10537. (function (BABYLON) {
  10538. /**
  10539. * @hidden
  10540. **/
  10541. var _DepthCullingState = /** @class */ (function () {
  10542. /**
  10543. * Initializes the state.
  10544. */
  10545. function _DepthCullingState() {
  10546. this._isDepthTestDirty = false;
  10547. this._isDepthMaskDirty = false;
  10548. this._isDepthFuncDirty = false;
  10549. this._isCullFaceDirty = false;
  10550. this._isCullDirty = false;
  10551. this._isZOffsetDirty = false;
  10552. this._isFrontFaceDirty = false;
  10553. this.reset();
  10554. }
  10555. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10556. get: function () {
  10557. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10558. },
  10559. enumerable: true,
  10560. configurable: true
  10561. });
  10562. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10563. get: function () {
  10564. return this._zOffset;
  10565. },
  10566. set: function (value) {
  10567. if (this._zOffset === value) {
  10568. return;
  10569. }
  10570. this._zOffset = value;
  10571. this._isZOffsetDirty = true;
  10572. },
  10573. enumerable: true,
  10574. configurable: true
  10575. });
  10576. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10577. get: function () {
  10578. return this._cullFace;
  10579. },
  10580. set: function (value) {
  10581. if (this._cullFace === value) {
  10582. return;
  10583. }
  10584. this._cullFace = value;
  10585. this._isCullFaceDirty = true;
  10586. },
  10587. enumerable: true,
  10588. configurable: true
  10589. });
  10590. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10591. get: function () {
  10592. return this._cull;
  10593. },
  10594. set: function (value) {
  10595. if (this._cull === value) {
  10596. return;
  10597. }
  10598. this._cull = value;
  10599. this._isCullDirty = true;
  10600. },
  10601. enumerable: true,
  10602. configurable: true
  10603. });
  10604. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10605. get: function () {
  10606. return this._depthFunc;
  10607. },
  10608. set: function (value) {
  10609. if (this._depthFunc === value) {
  10610. return;
  10611. }
  10612. this._depthFunc = value;
  10613. this._isDepthFuncDirty = true;
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10619. get: function () {
  10620. return this._depthMask;
  10621. },
  10622. set: function (value) {
  10623. if (this._depthMask === value) {
  10624. return;
  10625. }
  10626. this._depthMask = value;
  10627. this._isDepthMaskDirty = true;
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10633. get: function () {
  10634. return this._depthTest;
  10635. },
  10636. set: function (value) {
  10637. if (this._depthTest === value) {
  10638. return;
  10639. }
  10640. this._depthTest = value;
  10641. this._isDepthTestDirty = true;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10647. get: function () {
  10648. return this._frontFace;
  10649. },
  10650. set: function (value) {
  10651. if (this._frontFace === value) {
  10652. return;
  10653. }
  10654. this._frontFace = value;
  10655. this._isFrontFaceDirty = true;
  10656. },
  10657. enumerable: true,
  10658. configurable: true
  10659. });
  10660. _DepthCullingState.prototype.reset = function () {
  10661. this._depthMask = true;
  10662. this._depthTest = true;
  10663. this._depthFunc = null;
  10664. this._cullFace = null;
  10665. this._cull = null;
  10666. this._zOffset = 0;
  10667. this._frontFace = null;
  10668. this._isDepthTestDirty = true;
  10669. this._isDepthMaskDirty = true;
  10670. this._isDepthFuncDirty = false;
  10671. this._isCullFaceDirty = false;
  10672. this._isCullDirty = false;
  10673. this._isZOffsetDirty = false;
  10674. this._isFrontFaceDirty = false;
  10675. };
  10676. _DepthCullingState.prototype.apply = function (gl) {
  10677. if (!this.isDirty) {
  10678. return;
  10679. }
  10680. // Cull
  10681. if (this._isCullDirty) {
  10682. if (this.cull) {
  10683. gl.enable(gl.CULL_FACE);
  10684. }
  10685. else {
  10686. gl.disable(gl.CULL_FACE);
  10687. }
  10688. this._isCullDirty = false;
  10689. }
  10690. // Cull face
  10691. if (this._isCullFaceDirty) {
  10692. gl.cullFace(this.cullFace);
  10693. this._isCullFaceDirty = false;
  10694. }
  10695. // Depth mask
  10696. if (this._isDepthMaskDirty) {
  10697. gl.depthMask(this.depthMask);
  10698. this._isDepthMaskDirty = false;
  10699. }
  10700. // Depth test
  10701. if (this._isDepthTestDirty) {
  10702. if (this.depthTest) {
  10703. gl.enable(gl.DEPTH_TEST);
  10704. }
  10705. else {
  10706. gl.disable(gl.DEPTH_TEST);
  10707. }
  10708. this._isDepthTestDirty = false;
  10709. }
  10710. // Depth func
  10711. if (this._isDepthFuncDirty) {
  10712. gl.depthFunc(this.depthFunc);
  10713. this._isDepthFuncDirty = false;
  10714. }
  10715. // zOffset
  10716. if (this._isZOffsetDirty) {
  10717. if (this.zOffset) {
  10718. gl.enable(gl.POLYGON_OFFSET_FILL);
  10719. gl.polygonOffset(this.zOffset, 0);
  10720. }
  10721. else {
  10722. gl.disable(gl.POLYGON_OFFSET_FILL);
  10723. }
  10724. this._isZOffsetDirty = false;
  10725. }
  10726. // Front face
  10727. if (this._isFrontFaceDirty) {
  10728. gl.frontFace(this.frontFace);
  10729. this._isFrontFaceDirty = false;
  10730. }
  10731. };
  10732. return _DepthCullingState;
  10733. }());
  10734. BABYLON._DepthCullingState = _DepthCullingState;
  10735. })(BABYLON || (BABYLON = {}));
  10736. //# sourceMappingURL=babylon.depthCullingState.js.map
  10737. var BABYLON;
  10738. (function (BABYLON) {
  10739. /**
  10740. * @hidden
  10741. **/
  10742. var _StencilState = /** @class */ (function () {
  10743. function _StencilState() {
  10744. this._isStencilTestDirty = false;
  10745. this._isStencilMaskDirty = false;
  10746. this._isStencilFuncDirty = false;
  10747. this._isStencilOpDirty = false;
  10748. this.reset();
  10749. }
  10750. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10751. get: function () {
  10752. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10758. get: function () {
  10759. return this._stencilFunc;
  10760. },
  10761. set: function (value) {
  10762. if (this._stencilFunc === value) {
  10763. return;
  10764. }
  10765. this._stencilFunc = value;
  10766. this._isStencilFuncDirty = true;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10772. get: function () {
  10773. return this._stencilFuncRef;
  10774. },
  10775. set: function (value) {
  10776. if (this._stencilFuncRef === value) {
  10777. return;
  10778. }
  10779. this._stencilFuncRef = value;
  10780. this._isStencilFuncDirty = true;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10786. get: function () {
  10787. return this._stencilFuncMask;
  10788. },
  10789. set: function (value) {
  10790. if (this._stencilFuncMask === value) {
  10791. return;
  10792. }
  10793. this._stencilFuncMask = value;
  10794. this._isStencilFuncDirty = true;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10800. get: function () {
  10801. return this._stencilOpStencilFail;
  10802. },
  10803. set: function (value) {
  10804. if (this._stencilOpStencilFail === value) {
  10805. return;
  10806. }
  10807. this._stencilOpStencilFail = value;
  10808. this._isStencilOpDirty = true;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10814. get: function () {
  10815. return this._stencilOpDepthFail;
  10816. },
  10817. set: function (value) {
  10818. if (this._stencilOpDepthFail === value) {
  10819. return;
  10820. }
  10821. this._stencilOpDepthFail = value;
  10822. this._isStencilOpDirty = true;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10828. get: function () {
  10829. return this._stencilOpStencilDepthPass;
  10830. },
  10831. set: function (value) {
  10832. if (this._stencilOpStencilDepthPass === value) {
  10833. return;
  10834. }
  10835. this._stencilOpStencilDepthPass = value;
  10836. this._isStencilOpDirty = true;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10842. get: function () {
  10843. return this._stencilMask;
  10844. },
  10845. set: function (value) {
  10846. if (this._stencilMask === value) {
  10847. return;
  10848. }
  10849. this._stencilMask = value;
  10850. this._isStencilMaskDirty = true;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10856. get: function () {
  10857. return this._stencilTest;
  10858. },
  10859. set: function (value) {
  10860. if (this._stencilTest === value) {
  10861. return;
  10862. }
  10863. this._stencilTest = value;
  10864. this._isStencilTestDirty = true;
  10865. },
  10866. enumerable: true,
  10867. configurable: true
  10868. });
  10869. _StencilState.prototype.reset = function () {
  10870. this._stencilTest = false;
  10871. this._stencilMask = 0xFF;
  10872. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10873. this._stencilFuncRef = 1;
  10874. this._stencilFuncMask = 0xFF;
  10875. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10876. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10877. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10878. this._isStencilTestDirty = true;
  10879. this._isStencilMaskDirty = true;
  10880. this._isStencilFuncDirty = true;
  10881. this._isStencilOpDirty = true;
  10882. };
  10883. _StencilState.prototype.apply = function (gl) {
  10884. if (!this.isDirty) {
  10885. return;
  10886. }
  10887. // Stencil test
  10888. if (this._isStencilTestDirty) {
  10889. if (this.stencilTest) {
  10890. gl.enable(gl.STENCIL_TEST);
  10891. }
  10892. else {
  10893. gl.disable(gl.STENCIL_TEST);
  10894. }
  10895. this._isStencilTestDirty = false;
  10896. }
  10897. // Stencil mask
  10898. if (this._isStencilMaskDirty) {
  10899. gl.stencilMask(this.stencilMask);
  10900. this._isStencilMaskDirty = false;
  10901. }
  10902. // Stencil func
  10903. if (this._isStencilFuncDirty) {
  10904. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10905. this._isStencilFuncDirty = false;
  10906. }
  10907. // Stencil op
  10908. if (this._isStencilOpDirty) {
  10909. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10910. this._isStencilOpDirty = false;
  10911. }
  10912. };
  10913. return _StencilState;
  10914. }());
  10915. BABYLON._StencilState = _StencilState;
  10916. })(BABYLON || (BABYLON = {}));
  10917. //# sourceMappingURL=babylon.stencilState.js.map
  10918. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10919. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10920. s = arguments[i];
  10921. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10922. t[p] = s[p];
  10923. }
  10924. return t;
  10925. };
  10926. var BABYLON;
  10927. (function (BABYLON) {
  10928. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10929. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10930. };
  10931. var compileRawShader = function (gl, source, type) {
  10932. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10933. gl.shaderSource(shader, source);
  10934. gl.compileShader(shader);
  10935. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10936. var log = gl.getShaderInfoLog(shader);
  10937. if (log) {
  10938. throw new Error(log);
  10939. }
  10940. }
  10941. if (!shader) {
  10942. throw new Error("Something went wrong while compile the shader.");
  10943. }
  10944. return shader;
  10945. };
  10946. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10947. var magFilter = gl.NEAREST;
  10948. var minFilter = gl.NEAREST;
  10949. switch (samplingMode) {
  10950. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10951. magFilter = gl.LINEAR;
  10952. if (generateMipMaps) {
  10953. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10954. }
  10955. else {
  10956. minFilter = gl.LINEAR;
  10957. }
  10958. break;
  10959. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10960. magFilter = gl.LINEAR;
  10961. if (generateMipMaps) {
  10962. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10963. }
  10964. else {
  10965. minFilter = gl.LINEAR;
  10966. }
  10967. break;
  10968. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10969. magFilter = gl.NEAREST;
  10970. if (generateMipMaps) {
  10971. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10972. }
  10973. else {
  10974. minFilter = gl.NEAREST;
  10975. }
  10976. break;
  10977. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10978. magFilter = gl.NEAREST;
  10979. if (generateMipMaps) {
  10980. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10981. }
  10982. else {
  10983. minFilter = gl.NEAREST;
  10984. }
  10985. break;
  10986. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10987. magFilter = gl.NEAREST;
  10988. if (generateMipMaps) {
  10989. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10990. }
  10991. else {
  10992. minFilter = gl.LINEAR;
  10993. }
  10994. break;
  10995. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10996. magFilter = gl.NEAREST;
  10997. if (generateMipMaps) {
  10998. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10999. }
  11000. else {
  11001. minFilter = gl.LINEAR;
  11002. }
  11003. break;
  11004. case BABYLON.Texture.NEAREST_LINEAR:
  11005. magFilter = gl.NEAREST;
  11006. minFilter = gl.LINEAR;
  11007. break;
  11008. case BABYLON.Texture.NEAREST_NEAREST:
  11009. magFilter = gl.NEAREST;
  11010. minFilter = gl.NEAREST;
  11011. break;
  11012. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11013. magFilter = gl.LINEAR;
  11014. if (generateMipMaps) {
  11015. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11016. }
  11017. else {
  11018. minFilter = gl.NEAREST;
  11019. }
  11020. break;
  11021. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11022. magFilter = gl.LINEAR;
  11023. if (generateMipMaps) {
  11024. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11025. }
  11026. else {
  11027. minFilter = gl.NEAREST;
  11028. }
  11029. break;
  11030. case BABYLON.Texture.LINEAR_LINEAR:
  11031. magFilter = gl.LINEAR;
  11032. minFilter = gl.LINEAR;
  11033. break;
  11034. case BABYLON.Texture.LINEAR_NEAREST:
  11035. magFilter = gl.LINEAR;
  11036. minFilter = gl.NEAREST;
  11037. break;
  11038. }
  11039. return {
  11040. min: minFilter,
  11041. mag: magFilter
  11042. };
  11043. };
  11044. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11045. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11046. var img;
  11047. var onload = function () {
  11048. loadedImages[index] = img;
  11049. loadedImages._internalCount++;
  11050. if (scene) {
  11051. scene._removePendingData(img);
  11052. }
  11053. if (loadedImages._internalCount === 6) {
  11054. onfinish(loadedImages);
  11055. }
  11056. };
  11057. var onerror = function (message, exception) {
  11058. if (scene) {
  11059. scene._removePendingData(img);
  11060. }
  11061. if (onErrorCallBack) {
  11062. onErrorCallBack(message, exception);
  11063. }
  11064. };
  11065. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11066. if (scene) {
  11067. scene._addPendingData(img);
  11068. }
  11069. };
  11070. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11071. if (onError === void 0) { onError = null; }
  11072. var loadedImages = [];
  11073. loadedImages._internalCount = 0;
  11074. for (var index = 0; index < 6; index++) {
  11075. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11076. }
  11077. };
  11078. var BufferPointer = /** @class */ (function () {
  11079. function BufferPointer() {
  11080. }
  11081. return BufferPointer;
  11082. }());
  11083. /**
  11084. * Interface for attribute information associated with buffer instanciation
  11085. */
  11086. var InstancingAttributeInfo = /** @class */ (function () {
  11087. function InstancingAttributeInfo() {
  11088. }
  11089. return InstancingAttributeInfo;
  11090. }());
  11091. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11092. /**
  11093. * Define options used to create a render target texture
  11094. */
  11095. var RenderTargetCreationOptions = /** @class */ (function () {
  11096. function RenderTargetCreationOptions() {
  11097. }
  11098. return RenderTargetCreationOptions;
  11099. }());
  11100. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11101. /**
  11102. * Define options used to create a depth texture
  11103. */
  11104. var DepthTextureCreationOptions = /** @class */ (function () {
  11105. function DepthTextureCreationOptions() {
  11106. }
  11107. return DepthTextureCreationOptions;
  11108. }());
  11109. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11110. /**
  11111. * Class used to describe the capabilities of the engine relatively to the current browser
  11112. */
  11113. var EngineCapabilities = /** @class */ (function () {
  11114. function EngineCapabilities() {
  11115. }
  11116. return EngineCapabilities;
  11117. }());
  11118. BABYLON.EngineCapabilities = EngineCapabilities;
  11119. /**
  11120. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11121. */
  11122. var Engine = /** @class */ (function () {
  11123. /**
  11124. * Creates a new engine
  11125. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11126. * @param antialias defines enable antialiasing (default: false)
  11127. * @param options defines further options to be sent to the getContext() function
  11128. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11129. */
  11130. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11131. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11132. var _this = this;
  11133. // Public members
  11134. /**
  11135. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11136. */
  11137. this.forcePOTTextures = false;
  11138. /**
  11139. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11140. */
  11141. this.isFullscreen = false;
  11142. /**
  11143. * Gets a boolean indicating if the pointer is currently locked
  11144. */
  11145. this.isPointerLock = false;
  11146. /**
  11147. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11148. */
  11149. this.cullBackFaces = true;
  11150. /**
  11151. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11152. */
  11153. this.renderEvenInBackground = true;
  11154. /**
  11155. * Gets or sets a boolean indicating that cache can be kept between frames
  11156. */
  11157. this.preventCacheWipeBetweenFrames = false;
  11158. /**
  11159. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11160. **/
  11161. this.enableOfflineSupport = false;
  11162. /**
  11163. * 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)
  11164. **/
  11165. this.disableManifestCheck = false;
  11166. /**
  11167. * Gets the list of created scenes
  11168. */
  11169. this.scenes = new Array();
  11170. /**
  11171. * Gets the list of created postprocesses
  11172. */
  11173. this.postProcesses = new Array();
  11174. // Observables
  11175. /**
  11176. * Observable event triggered each time the rendering canvas is resized
  11177. */
  11178. this.onResizeObservable = new BABYLON.Observable();
  11179. /**
  11180. * Observable event triggered each time the canvas loses focus
  11181. */
  11182. this.onCanvasBlurObservable = new BABYLON.Observable();
  11183. /**
  11184. * Observable event triggered each time the canvas gains focus
  11185. */
  11186. this.onCanvasFocusObservable = new BABYLON.Observable();
  11187. /**
  11188. * Observable event triggered each time the canvas receives pointerout event
  11189. */
  11190. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11191. /**
  11192. * Observable event triggered before each texture is initialized
  11193. */
  11194. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11195. //WebVR
  11196. this._vrDisplay = undefined;
  11197. this._vrSupported = false;
  11198. this._vrExclusivePointerMode = false;
  11199. // Uniform buffers list
  11200. /**
  11201. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11202. */
  11203. this.disableUniformBuffers = false;
  11204. /** @hidden */
  11205. this._uniformBuffers = new Array();
  11206. // Observables
  11207. /**
  11208. * Observable raised when the engine begins a new frame
  11209. */
  11210. this.onBeginFrameObservable = new BABYLON.Observable();
  11211. /**
  11212. * Observable raised when the engine ends the current frame
  11213. */
  11214. this.onEndFrameObservable = new BABYLON.Observable();
  11215. /**
  11216. * Observable raised when the engine is about to compile a shader
  11217. */
  11218. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11219. /**
  11220. * Observable raised when the engine has jsut compiled a shader
  11221. */
  11222. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11223. this._windowIsBackground = false;
  11224. this._webGLVersion = 1.0;
  11225. /** @hidden */
  11226. this._badOS = false;
  11227. /** @hidden */
  11228. this._badDesktopOS = false;
  11229. /**
  11230. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11231. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11232. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11233. */
  11234. this.disableTextureBindingOptimization = false;
  11235. /**
  11236. * Observable signaled when VR display mode changes
  11237. */
  11238. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11239. /**
  11240. * Observable signaled when VR request present is complete
  11241. */
  11242. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11243. /**
  11244. * Observable signaled when VR request present starts
  11245. */
  11246. this.onVRRequestPresentStart = new BABYLON.Observable();
  11247. this._colorWrite = true;
  11248. /** @hidden */
  11249. this._drawCalls = new BABYLON.PerfCounter();
  11250. /** @hidden */
  11251. this._textureCollisions = new BABYLON.PerfCounter();
  11252. this._renderingQueueLaunched = false;
  11253. this._activeRenderLoops = new Array();
  11254. // Deterministic lockstepMaxSteps
  11255. this._deterministicLockstep = false;
  11256. this._lockstepMaxSteps = 4;
  11257. // Lost context
  11258. /**
  11259. * Observable signaled when a context lost event is raised
  11260. */
  11261. this.onContextLostObservable = new BABYLON.Observable();
  11262. /**
  11263. * Observable signaled when a context restored event is raised
  11264. */
  11265. this.onContextRestoredObservable = new BABYLON.Observable();
  11266. this._contextWasLost = false;
  11267. this._doNotHandleContextLost = false;
  11268. // FPS
  11269. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11270. this._fps = 60;
  11271. this._deltaTime = 0;
  11272. /**
  11273. * Turn this value on if you want to pause FPS computation when in background
  11274. */
  11275. this.disablePerformanceMonitorInBackground = false;
  11276. // States
  11277. /** @hidden */
  11278. this._depthCullingState = new BABYLON._DepthCullingState();
  11279. /** @hidden */
  11280. this._stencilState = new BABYLON._StencilState();
  11281. /** @hidden */
  11282. this._alphaState = new BABYLON._AlphaState();
  11283. /** @hidden */
  11284. this._alphaMode = Engine.ALPHA_DISABLE;
  11285. // Cache
  11286. this._internalTexturesCache = new Array();
  11287. /** @hidden */
  11288. this._activeChannel = 0;
  11289. this._currentTextureChannel = -1;
  11290. /** @hidden */
  11291. this._boundTexturesCache = {};
  11292. this._compiledEffects = {};
  11293. this._vertexAttribArraysEnabled = [];
  11294. this._uintIndicesCurrentlySet = false;
  11295. this._currentBoundBuffer = new Array();
  11296. this._currentBufferPointers = new Array();
  11297. this._currentInstanceLocations = new Array();
  11298. this._currentInstanceBuffers = new Array();
  11299. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11300. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11301. this._vaoRecordInProgress = false;
  11302. this._mustWipeVertexAttributes = false;
  11303. this._nextFreeTextureSlots = new Array();
  11304. this._maxSimultaneousTextures = 0;
  11305. this._activeRequests = new Array();
  11306. // Hardware supported Compressed Textures
  11307. this._texturesSupported = new Array();
  11308. this._onVRFullScreenTriggered = function () {
  11309. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11310. //get the old size before we change
  11311. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11312. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11313. //get the width and height, change the render size
  11314. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11315. _this.setHardwareScalingLevel(1);
  11316. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11317. }
  11318. else {
  11319. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11320. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11321. }
  11322. };
  11323. this._boundUniforms = {};
  11324. // Register promises
  11325. BABYLON.PromisePolyfill.Apply();
  11326. var canvas = null;
  11327. Engine.Instances.push(this);
  11328. if (!canvasOrContext) {
  11329. return;
  11330. }
  11331. options = options || {};
  11332. if (canvasOrContext.getContext) {
  11333. canvas = canvasOrContext;
  11334. this._renderingCanvas = canvas;
  11335. if (antialias != null) {
  11336. options.antialias = antialias;
  11337. }
  11338. if (options.deterministicLockstep === undefined) {
  11339. options.deterministicLockstep = false;
  11340. }
  11341. if (options.lockstepMaxSteps === undefined) {
  11342. options.lockstepMaxSteps = 4;
  11343. }
  11344. if (options.preserveDrawingBuffer === undefined) {
  11345. options.preserveDrawingBuffer = false;
  11346. }
  11347. if (options.audioEngine === undefined) {
  11348. options.audioEngine = true;
  11349. }
  11350. if (options.stencil === undefined) {
  11351. options.stencil = true;
  11352. }
  11353. this._deterministicLockstep = options.deterministicLockstep;
  11354. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11355. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11356. // Exceptions
  11357. if (navigator && navigator.userAgent) {
  11358. var ua = navigator.userAgent;
  11359. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11360. var exception = _a[_i];
  11361. var key = exception.key;
  11362. var targets = exception.targets;
  11363. if (ua.indexOf(key) > -1) {
  11364. if (exception.capture && exception.captureConstraint) {
  11365. var capture = exception.capture;
  11366. var constraint = exception.captureConstraint;
  11367. var regex = new RegExp(capture);
  11368. var matches = regex.exec(ua);
  11369. if (matches && matches.length > 0) {
  11370. var capturedValue = parseInt(matches[matches.length - 1]);
  11371. if (capturedValue >= constraint) {
  11372. continue;
  11373. }
  11374. }
  11375. }
  11376. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11377. var target = targets_1[_b];
  11378. switch (target) {
  11379. case "uniformBuffer":
  11380. this.disableUniformBuffers = true;
  11381. break;
  11382. case "textureBindingOptimization":
  11383. this.disableTextureBindingOptimization = true;
  11384. break;
  11385. }
  11386. }
  11387. }
  11388. }
  11389. }
  11390. // GL
  11391. if (!options.disableWebGL2Support) {
  11392. try {
  11393. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11394. if (this._gl) {
  11395. this._webGLVersion = 2.0;
  11396. }
  11397. }
  11398. catch (e) {
  11399. // Do nothing
  11400. }
  11401. }
  11402. if (!this._gl) {
  11403. if (!canvas) {
  11404. throw new Error("The provided canvas is null or undefined.");
  11405. }
  11406. try {
  11407. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11408. }
  11409. catch (e) {
  11410. throw new Error("WebGL not supported");
  11411. }
  11412. }
  11413. if (!this._gl) {
  11414. throw new Error("WebGL not supported");
  11415. }
  11416. this._onCanvasFocus = function () {
  11417. _this.onCanvasFocusObservable.notifyObservers(_this);
  11418. };
  11419. this._onCanvasBlur = function () {
  11420. _this.onCanvasBlurObservable.notifyObservers(_this);
  11421. };
  11422. canvas.addEventListener("focus", this._onCanvasFocus);
  11423. canvas.addEventListener("blur", this._onCanvasBlur);
  11424. this._onBlur = function () {
  11425. if (_this.disablePerformanceMonitorInBackground) {
  11426. _this._performanceMonitor.disable();
  11427. }
  11428. _this._windowIsBackground = true;
  11429. };
  11430. this._onFocus = function () {
  11431. if (_this.disablePerformanceMonitorInBackground) {
  11432. _this._performanceMonitor.enable();
  11433. }
  11434. _this._windowIsBackground = false;
  11435. };
  11436. this._onCanvasPointerOut = function (ev) {
  11437. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11438. };
  11439. window.addEventListener("blur", this._onBlur);
  11440. window.addEventListener("focus", this._onFocus);
  11441. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11442. // Context lost
  11443. if (!this._doNotHandleContextLost) {
  11444. this._onContextLost = function (evt) {
  11445. evt.preventDefault();
  11446. _this._contextWasLost = true;
  11447. BABYLON.Tools.Warn("WebGL context lost.");
  11448. _this.onContextLostObservable.notifyObservers(_this);
  11449. };
  11450. this._onContextRestored = function (evt) {
  11451. // Adding a timeout to avoid race condition at browser level
  11452. setTimeout(function () {
  11453. // Rebuild gl context
  11454. _this._initGLContext();
  11455. // Rebuild effects
  11456. _this._rebuildEffects();
  11457. // Rebuild textures
  11458. _this._rebuildInternalTextures();
  11459. // Rebuild buffers
  11460. _this._rebuildBuffers();
  11461. // Cache
  11462. _this.wipeCaches(true);
  11463. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11464. _this.onContextRestoredObservable.notifyObservers(_this);
  11465. _this._contextWasLost = false;
  11466. }, 0);
  11467. };
  11468. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11469. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11470. }
  11471. }
  11472. else {
  11473. this._gl = canvasOrContext;
  11474. this._renderingCanvas = this._gl.canvas;
  11475. if (this._gl.renderbufferStorageMultisample) {
  11476. this._webGLVersion = 2.0;
  11477. }
  11478. options.stencil = this._gl.getContextAttributes().stencil;
  11479. }
  11480. // Viewport
  11481. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11482. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11483. this.resize();
  11484. this._isStencilEnable = options.stencil ? true : false;
  11485. this._initGLContext();
  11486. if (canvas) {
  11487. // Fullscreen
  11488. this._onFullscreenChange = function () {
  11489. if (document.fullscreen !== undefined) {
  11490. _this.isFullscreen = document.fullscreen;
  11491. }
  11492. else if (document.mozFullScreen !== undefined) {
  11493. _this.isFullscreen = document.mozFullScreen;
  11494. }
  11495. else if (document.webkitIsFullScreen !== undefined) {
  11496. _this.isFullscreen = document.webkitIsFullScreen;
  11497. }
  11498. else if (document.msIsFullScreen !== undefined) {
  11499. _this.isFullscreen = document.msIsFullScreen;
  11500. }
  11501. // Pointer lock
  11502. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11503. canvas.requestPointerLock = canvas.requestPointerLock ||
  11504. canvas.msRequestPointerLock ||
  11505. canvas.mozRequestPointerLock ||
  11506. canvas.webkitRequestPointerLock;
  11507. if (canvas.requestPointerLock) {
  11508. canvas.requestPointerLock();
  11509. }
  11510. }
  11511. };
  11512. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11513. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11514. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11515. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11516. // Pointer lock
  11517. this._onPointerLockChange = function () {
  11518. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11519. document.webkitPointerLockElement === canvas ||
  11520. document.msPointerLockElement === canvas ||
  11521. document.pointerLockElement === canvas);
  11522. };
  11523. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11524. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11525. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11526. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11527. this._onVRDisplayPointerRestricted = function () {
  11528. if (canvas) {
  11529. canvas.requestPointerLock();
  11530. }
  11531. };
  11532. this._onVRDisplayPointerUnrestricted = function () {
  11533. document.exitPointerLock();
  11534. };
  11535. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11536. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11537. }
  11538. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11539. Engine.audioEngine = new BABYLON.AudioEngine();
  11540. }
  11541. // Prepare buffer pointers
  11542. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11543. this._currentBufferPointers[i] = new BufferPointer();
  11544. }
  11545. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11546. // Load WebVR Devices
  11547. if (options.autoEnableWebVR) {
  11548. this.initWebVR();
  11549. }
  11550. // Detect if we are running on a faulty buggy OS.
  11551. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11552. // Detect if we are running on a faulty buggy desktop OS.
  11553. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11554. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11555. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11556. }
  11557. Object.defineProperty(Engine, "LastCreatedEngine", {
  11558. /**
  11559. * Gets the latest created engine
  11560. */
  11561. get: function () {
  11562. if (Engine.Instances.length === 0) {
  11563. return null;
  11564. }
  11565. return Engine.Instances[Engine.Instances.length - 1];
  11566. },
  11567. enumerable: true,
  11568. configurable: true
  11569. });
  11570. Object.defineProperty(Engine, "LastCreatedScene", {
  11571. /**
  11572. * Gets the latest created scene
  11573. */
  11574. get: function () {
  11575. var lastCreatedEngine = Engine.LastCreatedEngine;
  11576. if (!lastCreatedEngine) {
  11577. return null;
  11578. }
  11579. if (lastCreatedEngine.scenes.length === 0) {
  11580. return null;
  11581. }
  11582. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11583. },
  11584. enumerable: true,
  11585. configurable: true
  11586. });
  11587. /**
  11588. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11589. * @param flag defines which part of the materials must be marked as dirty
  11590. * @param predicate defines a predicate used to filter which materials should be affected
  11591. */
  11592. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11593. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11594. var engine = Engine.Instances[engineIndex];
  11595. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11596. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11597. }
  11598. }
  11599. };
  11600. Object.defineProperty(Engine, "NEVER", {
  11601. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11602. get: function () {
  11603. return Engine._NEVER;
  11604. },
  11605. enumerable: true,
  11606. configurable: true
  11607. });
  11608. Object.defineProperty(Engine, "ALWAYS", {
  11609. /** 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 */
  11610. get: function () {
  11611. return Engine._ALWAYS;
  11612. },
  11613. enumerable: true,
  11614. configurable: true
  11615. });
  11616. Object.defineProperty(Engine, "LESS", {
  11617. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11618. get: function () {
  11619. return Engine._LESS;
  11620. },
  11621. enumerable: true,
  11622. configurable: true
  11623. });
  11624. Object.defineProperty(Engine, "EQUAL", {
  11625. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11626. get: function () {
  11627. return Engine._EQUAL;
  11628. },
  11629. enumerable: true,
  11630. configurable: true
  11631. });
  11632. Object.defineProperty(Engine, "LEQUAL", {
  11633. /** 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 */
  11634. get: function () {
  11635. return Engine._LEQUAL;
  11636. },
  11637. enumerable: true,
  11638. configurable: true
  11639. });
  11640. Object.defineProperty(Engine, "GREATER", {
  11641. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11642. get: function () {
  11643. return Engine._GREATER;
  11644. },
  11645. enumerable: true,
  11646. configurable: true
  11647. });
  11648. Object.defineProperty(Engine, "GEQUAL", {
  11649. /** 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 */
  11650. get: function () {
  11651. return Engine._GEQUAL;
  11652. },
  11653. enumerable: true,
  11654. configurable: true
  11655. });
  11656. Object.defineProperty(Engine, "NOTEQUAL", {
  11657. /** 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 */
  11658. get: function () {
  11659. return Engine._NOTEQUAL;
  11660. },
  11661. enumerable: true,
  11662. configurable: true
  11663. });
  11664. Object.defineProperty(Engine, "KEEP", {
  11665. /** Passed to stencilOperation to specify that stencil value must be kept */
  11666. get: function () {
  11667. return Engine._KEEP;
  11668. },
  11669. enumerable: true,
  11670. configurable: true
  11671. });
  11672. Object.defineProperty(Engine, "REPLACE", {
  11673. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11674. get: function () {
  11675. return Engine._REPLACE;
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. Object.defineProperty(Engine, "INCR", {
  11681. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11682. get: function () {
  11683. return Engine._INCR;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine, "DECR", {
  11689. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11690. get: function () {
  11691. return Engine._DECR;
  11692. },
  11693. enumerable: true,
  11694. configurable: true
  11695. });
  11696. Object.defineProperty(Engine, "INVERT", {
  11697. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11698. get: function () {
  11699. return Engine._INVERT;
  11700. },
  11701. enumerable: true,
  11702. configurable: true
  11703. });
  11704. Object.defineProperty(Engine, "INCR_WRAP", {
  11705. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11706. get: function () {
  11707. return Engine._INCR_WRAP;
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Engine, "DECR_WRAP", {
  11713. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11714. get: function () {
  11715. return Engine._DECR_WRAP;
  11716. },
  11717. enumerable: true,
  11718. configurable: true
  11719. });
  11720. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11721. // Alpha
  11722. /** Defines that alpha blending is disabled */
  11723. get: function () {
  11724. return Engine._ALPHA_DISABLE;
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11730. /** Defines that alpha blending to SRC + DEST */
  11731. get: function () {
  11732. return Engine._ALPHA_ONEONE;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine, "ALPHA_ADD", {
  11738. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11739. get: function () {
  11740. return Engine._ALPHA_ADD;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11746. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11747. get: function () {
  11748. return Engine._ALPHA_COMBINE;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11754. /** Defines that alpha blending to DEST - SRC * DEST */
  11755. get: function () {
  11756. return Engine._ALPHA_SUBTRACT;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11762. /** Defines that alpha blending to SRC * DEST */
  11763. get: function () {
  11764. return Engine._ALPHA_MULTIPLY;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11770. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11771. get: function () {
  11772. return Engine._ALPHA_MAXIMIZED;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11778. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11779. get: function () {
  11780. return Engine._ALPHA_PREMULTIPLIED;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11786. /**
  11787. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11788. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11789. */
  11790. get: function () {
  11791. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11797. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11798. get: function () {
  11799. return Engine._ALPHA_INTERPOLATE;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11805. /**
  11806. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11807. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11808. */
  11809. get: function () {
  11810. return Engine._ALPHA_SCREENMODE;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11816. // Delays
  11817. /** Defines that the ressource is not delayed*/
  11818. get: function () {
  11819. return Engine._DELAYLOADSTATE_NONE;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11825. /** Defines that the ressource was successfully delay loaded */
  11826. get: function () {
  11827. return Engine._DELAYLOADSTATE_LOADED;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11833. /** Defines that the ressource is currently delay loading */
  11834. get: function () {
  11835. return Engine._DELAYLOADSTATE_LOADING;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11841. /** Defines that the ressource is delayed and has not started loading */
  11842. get: function () {
  11843. return Engine._DELAYLOADSTATE_NOTLOADED;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11849. /** ALPHA */
  11850. get: function () {
  11851. return Engine._TEXTUREFORMAT_ALPHA;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11857. /** LUMINANCE */
  11858. get: function () {
  11859. return Engine._TEXTUREFORMAT_LUMINANCE;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11865. /**
  11866. * R32F
  11867. */
  11868. get: function () {
  11869. return Engine._TEXTUREFORMAT_R32F;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11875. /**
  11876. * RG32F
  11877. */
  11878. get: function () {
  11879. return Engine._TEXTUREFORMAT_RG32F;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11885. /**
  11886. * RGB32F
  11887. */
  11888. get: function () {
  11889. return Engine._TEXTUREFORMAT_RGB32F;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11895. /**
  11896. * RGBA32F
  11897. */
  11898. get: function () {
  11899. return Engine._TEXTUREFORMAT_RGBA32F;
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11905. /** LUMINANCE_ALPHA */
  11906. get: function () {
  11907. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11913. /** RGB */
  11914. get: function () {
  11915. return Engine._TEXTUREFORMAT_RGB;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11921. /** RGBA */
  11922. get: function () {
  11923. return Engine._TEXTUREFORMAT_RGBA;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11929. /** UNSIGNED_INT */
  11930. get: function () {
  11931. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11937. /** FLOAT */
  11938. get: function () {
  11939. return Engine._TEXTURETYPE_FLOAT;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11945. /** HALF_FLOAT */
  11946. get: function () {
  11947. return Engine._TEXTURETYPE_HALF_FLOAT;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11953. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11954. get: function () {
  11955. return Engine._SCALEMODE_FLOOR;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11961. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11962. get: function () {
  11963. return Engine._SCALEMODE_NEAREST;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11969. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11970. get: function () {
  11971. return Engine._SCALEMODE_CEILING;
  11972. },
  11973. enumerable: true,
  11974. configurable: true
  11975. });
  11976. Object.defineProperty(Engine, "Version", {
  11977. /**
  11978. * Returns the current version of the framework
  11979. */
  11980. get: function () {
  11981. return "3.3.0-alpha.0";
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11987. /**
  11988. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11989. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11990. */
  11991. get: function () {
  11992. return this._vrExclusivePointerMode;
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11998. /**
  11999. * Gets a boolean indicating that the engine supports uniform buffers
  12000. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12001. */
  12002. get: function () {
  12003. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12004. },
  12005. enumerable: true,
  12006. configurable: true
  12007. });
  12008. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12009. /**
  12010. * Gets a boolean indicating that only power of 2 textures are supported
  12011. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12012. */
  12013. get: function () {
  12014. return this._webGLVersion < 2 || this.forcePOTTextures;
  12015. },
  12016. enumerable: true,
  12017. configurable: true
  12018. });
  12019. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12020. /**
  12021. * Gets the performance monitor attached to this engine
  12022. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12023. */
  12024. get: function () {
  12025. return this._performanceMonitor;
  12026. },
  12027. enumerable: true,
  12028. configurable: true
  12029. });
  12030. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12031. /**
  12032. * Gets the list of texture formats supported
  12033. */
  12034. get: function () {
  12035. return this._texturesSupported;
  12036. },
  12037. enumerable: true,
  12038. configurable: true
  12039. });
  12040. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12041. /**
  12042. * Gets the list of texture formats in use
  12043. */
  12044. get: function () {
  12045. return this._textureFormatInUse;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Engine.prototype, "currentViewport", {
  12051. /**
  12052. * Gets the current viewport
  12053. */
  12054. get: function () {
  12055. return this._cachedViewport;
  12056. },
  12057. enumerable: true,
  12058. configurable: true
  12059. });
  12060. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12061. /**
  12062. * Gets the default empty texture
  12063. */
  12064. get: function () {
  12065. if (!this._emptyTexture) {
  12066. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12067. }
  12068. return this._emptyTexture;
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12074. /**
  12075. * Gets the default empty 3D texture
  12076. */
  12077. get: function () {
  12078. if (!this._emptyTexture3D) {
  12079. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12080. }
  12081. return this._emptyTexture3D;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12087. /**
  12088. * Gets the default empty cube texture
  12089. */
  12090. get: function () {
  12091. if (!this._emptyCubeTexture) {
  12092. var faceData = new Uint8Array(4);
  12093. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12094. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12095. }
  12096. return this._emptyCubeTexture;
  12097. },
  12098. enumerable: true,
  12099. configurable: true
  12100. });
  12101. Engine.prototype._rebuildInternalTextures = function () {
  12102. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12103. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12104. var internalTexture = currentState_1[_i];
  12105. internalTexture._rebuild();
  12106. }
  12107. };
  12108. Engine.prototype._rebuildEffects = function () {
  12109. for (var key in this._compiledEffects) {
  12110. var effect = this._compiledEffects[key];
  12111. effect._prepareEffect();
  12112. }
  12113. BABYLON.Effect.ResetCache();
  12114. };
  12115. Engine.prototype._rebuildBuffers = function () {
  12116. // Index / Vertex
  12117. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12118. var scene = _a[_i];
  12119. scene.resetCachedMaterial();
  12120. scene._rebuildGeometries();
  12121. scene._rebuildTextures();
  12122. }
  12123. // Uniforms
  12124. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12125. var uniformBuffer = _c[_b];
  12126. uniformBuffer._rebuild();
  12127. }
  12128. };
  12129. Engine.prototype._initGLContext = function () {
  12130. // Caps
  12131. this._caps = new EngineCapabilities();
  12132. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12133. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12134. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12135. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12136. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12137. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12138. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12139. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12140. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12141. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12142. // Infos
  12143. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12144. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12145. if (rendererInfo != null) {
  12146. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12147. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12148. }
  12149. if (!this._glVendor) {
  12150. this._glVendor = "Unknown vendor";
  12151. }
  12152. if (!this._glRenderer) {
  12153. this._glRenderer = "Unknown renderer";
  12154. }
  12155. // Constants
  12156. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12157. if (this._gl.RGBA16F !== 0x881A) {
  12158. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12159. }
  12160. if (this._gl.RGBA32F !== 0x8814) {
  12161. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12162. }
  12163. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12164. this._gl.DEPTH24_STENCIL8 = 35056;
  12165. }
  12166. // Extensions
  12167. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12168. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12169. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12170. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12171. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12172. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12173. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12174. 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');
  12175. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12176. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12177. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12178. this._caps.highPrecisionShaderSupported = true;
  12179. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12180. if (this._caps.timerQuery) {
  12181. if (this._webGLVersion === 1) {
  12182. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12183. }
  12184. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12185. }
  12186. // Checks if some of the format renders first to allow the use of webgl inspector.
  12187. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12188. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12189. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12190. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12191. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12192. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12193. if (this._webGLVersion > 1) {
  12194. this._gl.HALF_FLOAT_OES = 0x140B;
  12195. }
  12196. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12197. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12198. // Draw buffers
  12199. if (this._webGLVersion > 1) {
  12200. this._caps.drawBuffersExtension = true;
  12201. }
  12202. else {
  12203. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12204. if (drawBuffersExtension !== null) {
  12205. this._caps.drawBuffersExtension = true;
  12206. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12207. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12208. for (var i = 0; i < 16; i++) {
  12209. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12210. }
  12211. }
  12212. else {
  12213. this._caps.drawBuffersExtension = false;
  12214. }
  12215. }
  12216. // Depth Texture
  12217. if (this._webGLVersion > 1) {
  12218. this._caps.depthTextureExtension = true;
  12219. }
  12220. else {
  12221. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12222. if (depthTextureExtension != null) {
  12223. this._caps.depthTextureExtension = true;
  12224. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12225. }
  12226. }
  12227. // Vertex array object
  12228. if (this._webGLVersion > 1) {
  12229. this._caps.vertexArrayObject = true;
  12230. }
  12231. else {
  12232. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12233. if (vertexArrayObjectExtension != null) {
  12234. this._caps.vertexArrayObject = true;
  12235. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12236. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12237. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12238. }
  12239. else {
  12240. this._caps.vertexArrayObject = false;
  12241. }
  12242. }
  12243. // Instances count
  12244. if (this._webGLVersion > 1) {
  12245. this._caps.instancedArrays = true;
  12246. }
  12247. else {
  12248. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12249. if (instanceExtension != null) {
  12250. this._caps.instancedArrays = true;
  12251. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12252. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12253. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12254. }
  12255. else {
  12256. this._caps.instancedArrays = false;
  12257. }
  12258. }
  12259. // Intelligently add supported compressed formats in order to check for.
  12260. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12261. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12262. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12263. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12264. if (this._caps.astc)
  12265. this.texturesSupported.push('-astc.ktx');
  12266. if (this._caps.s3tc)
  12267. this.texturesSupported.push('-dxt.ktx');
  12268. if (this._caps.pvrtc)
  12269. this.texturesSupported.push('-pvrtc.ktx');
  12270. if (this._caps.etc2)
  12271. this.texturesSupported.push('-etc2.ktx');
  12272. if (this._caps.etc1)
  12273. this.texturesSupported.push('-etc1.ktx');
  12274. if (this._gl.getShaderPrecisionFormat) {
  12275. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12276. if (highp) {
  12277. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12278. }
  12279. }
  12280. // Depth buffer
  12281. this.setDepthBuffer(true);
  12282. this.setDepthFunctionToLessOrEqual();
  12283. this.setDepthWrite(true);
  12284. // Texture maps
  12285. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12286. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12287. this._nextFreeTextureSlots.push(slot);
  12288. }
  12289. };
  12290. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12291. /**
  12292. * Gets version of the current webGL context
  12293. */
  12294. get: function () {
  12295. return this._webGLVersion;
  12296. },
  12297. enumerable: true,
  12298. configurable: true
  12299. });
  12300. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12301. /**
  12302. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12303. */
  12304. get: function () {
  12305. return this._isStencilEnable;
  12306. },
  12307. enumerable: true,
  12308. configurable: true
  12309. });
  12310. Engine.prototype._prepareWorkingCanvas = function () {
  12311. if (this._workingCanvas) {
  12312. return;
  12313. }
  12314. this._workingCanvas = document.createElement("canvas");
  12315. var context = this._workingCanvas.getContext("2d");
  12316. if (context) {
  12317. this._workingContext = context;
  12318. }
  12319. };
  12320. /**
  12321. * Reset the texture cache to empty state
  12322. */
  12323. Engine.prototype.resetTextureCache = function () {
  12324. for (var key in this._boundTexturesCache) {
  12325. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12326. continue;
  12327. }
  12328. var boundTexture = this._boundTexturesCache[key];
  12329. if (boundTexture) {
  12330. this._removeDesignatedSlot(boundTexture);
  12331. }
  12332. this._boundTexturesCache[key] = null;
  12333. }
  12334. if (!this.disableTextureBindingOptimization) {
  12335. this._nextFreeTextureSlots = [];
  12336. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12337. this._nextFreeTextureSlots.push(slot);
  12338. }
  12339. }
  12340. this._currentTextureChannel = -1;
  12341. };
  12342. /**
  12343. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12344. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12345. * @returns true if engine is in deterministic lock step mode
  12346. */
  12347. Engine.prototype.isDeterministicLockStep = function () {
  12348. return this._deterministicLockstep;
  12349. };
  12350. /**
  12351. * Gets the max steps when engine is running in deterministic lock step
  12352. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12353. * @returns the max steps
  12354. */
  12355. Engine.prototype.getLockstepMaxSteps = function () {
  12356. return this._lockstepMaxSteps;
  12357. };
  12358. /**
  12359. * Gets an object containing information about the current webGL context
  12360. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12361. */
  12362. Engine.prototype.getGlInfo = function () {
  12363. return {
  12364. vendor: this._glVendor,
  12365. renderer: this._glRenderer,
  12366. version: this._glVersion
  12367. };
  12368. };
  12369. /**
  12370. * Gets current aspect ratio
  12371. * @param camera defines the camera to use to get the aspect ratio
  12372. * @param useScreen defines if screen size must be used (or the current render target if any)
  12373. * @returns a number defining the aspect ratio
  12374. */
  12375. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12376. if (useScreen === void 0) { useScreen = false; }
  12377. var viewport = camera.viewport;
  12378. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12379. };
  12380. /**
  12381. * Gets current screen aspect ratio
  12382. * @returns a number defining the aspect ratio
  12383. */
  12384. Engine.prototype.getScreenAspectRatio = function () {
  12385. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12386. };
  12387. /**
  12388. * Gets the current render width
  12389. * @param useScreen defines if screen size must be used (or the current render target if any)
  12390. * @returns a number defining the current render width
  12391. */
  12392. Engine.prototype.getRenderWidth = function (useScreen) {
  12393. if (useScreen === void 0) { useScreen = false; }
  12394. if (!useScreen && this._currentRenderTarget) {
  12395. return this._currentRenderTarget.width;
  12396. }
  12397. return this._gl.drawingBufferWidth;
  12398. };
  12399. /**
  12400. * Gets the current render height
  12401. * @param useScreen defines if screen size must be used (or the current render target if any)
  12402. * @returns a number defining the current render height
  12403. */
  12404. Engine.prototype.getRenderHeight = function (useScreen) {
  12405. if (useScreen === void 0) { useScreen = false; }
  12406. if (!useScreen && this._currentRenderTarget) {
  12407. return this._currentRenderTarget.height;
  12408. }
  12409. return this._gl.drawingBufferHeight;
  12410. };
  12411. /**
  12412. * Gets the HTML canvas attached with the current webGL context
  12413. * @returns a HTML canvas
  12414. */
  12415. Engine.prototype.getRenderingCanvas = function () {
  12416. return this._renderingCanvas;
  12417. };
  12418. /**
  12419. * Gets the client rect of the HTML canvas attached with the current webGL context
  12420. * @returns a client rectanglee
  12421. */
  12422. Engine.prototype.getRenderingCanvasClientRect = function () {
  12423. if (!this._renderingCanvas) {
  12424. return null;
  12425. }
  12426. return this._renderingCanvas.getBoundingClientRect();
  12427. };
  12428. /**
  12429. * Defines the hardware scaling level.
  12430. * By default the hardware scaling level is computed from the window device ratio.
  12431. * 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.
  12432. * @param level defines the level to use
  12433. */
  12434. Engine.prototype.setHardwareScalingLevel = function (level) {
  12435. this._hardwareScalingLevel = level;
  12436. this.resize();
  12437. };
  12438. /**
  12439. * Gets the current hardware scaling level.
  12440. * By default the hardware scaling level is computed from the window device ratio.
  12441. * 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.
  12442. * @returns a number indicating the current hardware scaling level
  12443. */
  12444. Engine.prototype.getHardwareScalingLevel = function () {
  12445. return this._hardwareScalingLevel;
  12446. };
  12447. /**
  12448. * Gets the list of loaded textures
  12449. * @returns an array containing all loaded textures
  12450. */
  12451. Engine.prototype.getLoadedTexturesCache = function () {
  12452. return this._internalTexturesCache;
  12453. };
  12454. /**
  12455. * Gets the object containing all engine capabilities
  12456. * @returns the EngineCapabilities object
  12457. */
  12458. Engine.prototype.getCaps = function () {
  12459. return this._caps;
  12460. };
  12461. Object.defineProperty(Engine.prototype, "drawCalls", {
  12462. /** @hidden */
  12463. get: function () {
  12464. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12465. return 0;
  12466. },
  12467. enumerable: true,
  12468. configurable: true
  12469. });
  12470. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12471. /** @hidden */
  12472. get: function () {
  12473. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12474. return null;
  12475. },
  12476. enumerable: true,
  12477. configurable: true
  12478. });
  12479. /**
  12480. * Gets the current depth function
  12481. * @returns a number defining the depth function
  12482. */
  12483. Engine.prototype.getDepthFunction = function () {
  12484. return this._depthCullingState.depthFunc;
  12485. };
  12486. /**
  12487. * Sets the current depth function
  12488. * @param depthFunc defines the function to use
  12489. */
  12490. Engine.prototype.setDepthFunction = function (depthFunc) {
  12491. this._depthCullingState.depthFunc = depthFunc;
  12492. };
  12493. /**
  12494. * Sets the current depth function to GREATER
  12495. */
  12496. Engine.prototype.setDepthFunctionToGreater = function () {
  12497. this._depthCullingState.depthFunc = this._gl.GREATER;
  12498. };
  12499. /**
  12500. * Sets the current depth function to GEQUAL
  12501. */
  12502. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12503. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12504. };
  12505. /**
  12506. * Sets the current depth function to LESS
  12507. */
  12508. Engine.prototype.setDepthFunctionToLess = function () {
  12509. this._depthCullingState.depthFunc = this._gl.LESS;
  12510. };
  12511. /**
  12512. * Sets the current depth function to LEQUAL
  12513. */
  12514. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12515. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12516. };
  12517. /**
  12518. * Gets a boolean indicating if stencil buffer is enabled
  12519. * @returns the current stencil buffer state
  12520. */
  12521. Engine.prototype.getStencilBuffer = function () {
  12522. return this._stencilState.stencilTest;
  12523. };
  12524. /**
  12525. * Enable or disable the stencil buffer
  12526. * @param enable defines if the stencil buffer must be enabled or disabled
  12527. */
  12528. Engine.prototype.setStencilBuffer = function (enable) {
  12529. this._stencilState.stencilTest = enable;
  12530. };
  12531. /**
  12532. * Gets the current stencil mask
  12533. * @returns a number defining the new stencil mask to use
  12534. */
  12535. Engine.prototype.getStencilMask = function () {
  12536. return this._stencilState.stencilMask;
  12537. };
  12538. /**
  12539. * Sets the current stencil mask
  12540. * @param mask defines the new stencil mask to use
  12541. */
  12542. Engine.prototype.setStencilMask = function (mask) {
  12543. this._stencilState.stencilMask = mask;
  12544. };
  12545. /**
  12546. * Gets the current stencil function
  12547. * @returns a number defining the stencil function to use
  12548. */
  12549. Engine.prototype.getStencilFunction = function () {
  12550. return this._stencilState.stencilFunc;
  12551. };
  12552. /**
  12553. * Gets the current stencil reference value
  12554. * @returns a number defining the stencil reference value to use
  12555. */
  12556. Engine.prototype.getStencilFunctionReference = function () {
  12557. return this._stencilState.stencilFuncRef;
  12558. };
  12559. /**
  12560. * Gets the current stencil mask
  12561. * @returns a number defining the stencil mask to use
  12562. */
  12563. Engine.prototype.getStencilFunctionMask = function () {
  12564. return this._stencilState.stencilFuncMask;
  12565. };
  12566. /**
  12567. * Sets the current stencil function
  12568. * @param stencilFunc defines the new stencil function to use
  12569. */
  12570. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12571. this._stencilState.stencilFunc = stencilFunc;
  12572. };
  12573. /**
  12574. * Sets the current stencil reference
  12575. * @param reference defines the new stencil reference to use
  12576. */
  12577. Engine.prototype.setStencilFunctionReference = function (reference) {
  12578. this._stencilState.stencilFuncRef = reference;
  12579. };
  12580. /**
  12581. * Sets the current stencil mask
  12582. * @param mask defines the new stencil mask to use
  12583. */
  12584. Engine.prototype.setStencilFunctionMask = function (mask) {
  12585. this._stencilState.stencilFuncMask = mask;
  12586. };
  12587. /**
  12588. * Gets the current stencil operation when stencil fails
  12589. * @returns a number defining stencil operation to use when stencil fails
  12590. */
  12591. Engine.prototype.getStencilOperationFail = function () {
  12592. return this._stencilState.stencilOpStencilFail;
  12593. };
  12594. /**
  12595. * Gets the current stencil operation when depth fails
  12596. * @returns a number defining stencil operation to use when depth fails
  12597. */
  12598. Engine.prototype.getStencilOperationDepthFail = function () {
  12599. return this._stencilState.stencilOpDepthFail;
  12600. };
  12601. /**
  12602. * Gets the current stencil operation when stencil passes
  12603. * @returns a number defining stencil operation to use when stencil passes
  12604. */
  12605. Engine.prototype.getStencilOperationPass = function () {
  12606. return this._stencilState.stencilOpStencilDepthPass;
  12607. };
  12608. /**
  12609. * Sets the stencil operation to use when stencil fails
  12610. * @param operation defines the stencil operation to use when stencil fails
  12611. */
  12612. Engine.prototype.setStencilOperationFail = function (operation) {
  12613. this._stencilState.stencilOpStencilFail = operation;
  12614. };
  12615. /**
  12616. * Sets the stencil operation to use when depth fails
  12617. * @param operation defines the stencil operation to use when depth fails
  12618. */
  12619. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12620. this._stencilState.stencilOpDepthFail = operation;
  12621. };
  12622. /**
  12623. * Sets the stencil operation to use when stencil passes
  12624. * @param operation defines the stencil operation to use when stencil passes
  12625. */
  12626. Engine.prototype.setStencilOperationPass = function (operation) {
  12627. this._stencilState.stencilOpStencilDepthPass = operation;
  12628. };
  12629. /**
  12630. * Sets a boolean indicating if the dithering state is enabled or disabled
  12631. * @param value defines the dithering state
  12632. */
  12633. Engine.prototype.setDitheringState = function (value) {
  12634. if (value) {
  12635. this._gl.enable(this._gl.DITHER);
  12636. }
  12637. else {
  12638. this._gl.disable(this._gl.DITHER);
  12639. }
  12640. };
  12641. /**
  12642. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12643. * @param value defines the rasterizer state
  12644. */
  12645. Engine.prototype.setRasterizerState = function (value) {
  12646. if (value) {
  12647. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12648. }
  12649. else {
  12650. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12651. }
  12652. };
  12653. /**
  12654. * stop executing a render loop function and remove it from the execution array
  12655. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12656. */
  12657. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12658. if (!renderFunction) {
  12659. this._activeRenderLoops = [];
  12660. return;
  12661. }
  12662. var index = this._activeRenderLoops.indexOf(renderFunction);
  12663. if (index >= 0) {
  12664. this._activeRenderLoops.splice(index, 1);
  12665. }
  12666. };
  12667. /** @hidden */
  12668. Engine.prototype._renderLoop = function () {
  12669. if (!this._contextWasLost) {
  12670. var shouldRender = true;
  12671. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12672. shouldRender = false;
  12673. }
  12674. if (shouldRender) {
  12675. // Start new frame
  12676. this.beginFrame();
  12677. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12678. var renderFunction = this._activeRenderLoops[index];
  12679. renderFunction();
  12680. }
  12681. // Present
  12682. this.endFrame();
  12683. }
  12684. }
  12685. if (this._activeRenderLoops.length > 0) {
  12686. // Register new frame
  12687. var requester = null;
  12688. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12689. requester = this._vrDisplay;
  12690. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12691. }
  12692. else {
  12693. this._renderingQueueLaunched = false;
  12694. }
  12695. };
  12696. /**
  12697. * Register and execute a render loop. The engine can have more than one render function
  12698. * @param renderFunction defines the function to continuously execute
  12699. */
  12700. Engine.prototype.runRenderLoop = function (renderFunction) {
  12701. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12702. return;
  12703. }
  12704. this._activeRenderLoops.push(renderFunction);
  12705. if (!this._renderingQueueLaunched) {
  12706. this._renderingQueueLaunched = true;
  12707. this._bindedRenderFunction = this._renderLoop.bind(this);
  12708. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12709. }
  12710. };
  12711. /**
  12712. * Toggle full screen mode
  12713. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12714. * @param options defines an option object to be sent to the requestFullscreen function
  12715. */
  12716. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12717. if (this.isFullscreen) {
  12718. BABYLON.Tools.ExitFullscreen();
  12719. }
  12720. else {
  12721. this._pointerLockRequested = requestPointerLock;
  12722. if (this._renderingCanvas) {
  12723. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12724. }
  12725. }
  12726. };
  12727. /**
  12728. * Clear the current render buffer or the current render target (if any is set up)
  12729. * @param color defines the color to use
  12730. * @param backBuffer defines if the back buffer must be cleared
  12731. * @param depth defines if the depth buffer must be cleared
  12732. * @param stencil defines if the stencil buffer must be cleared
  12733. */
  12734. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12735. if (stencil === void 0) { stencil = false; }
  12736. this.applyStates();
  12737. var mode = 0;
  12738. if (backBuffer && color) {
  12739. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12740. mode |= this._gl.COLOR_BUFFER_BIT;
  12741. }
  12742. if (depth) {
  12743. this._gl.clearDepth(1.0);
  12744. mode |= this._gl.DEPTH_BUFFER_BIT;
  12745. }
  12746. if (stencil) {
  12747. this._gl.clearStencil(0);
  12748. mode |= this._gl.STENCIL_BUFFER_BIT;
  12749. }
  12750. this._gl.clear(mode);
  12751. };
  12752. /**
  12753. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12754. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12755. * @param y defines the y-coordinate of the corner of the clear rectangle
  12756. * @param width defines the width of the clear rectangle
  12757. * @param height defines the height of the clear rectangle
  12758. * @param clearColor defines the clear color
  12759. */
  12760. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12761. var gl = this._gl;
  12762. // Save state
  12763. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12764. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12765. // Change state
  12766. gl.enable(gl.SCISSOR_TEST);
  12767. gl.scissor(x, y, width, height);
  12768. // Clear
  12769. this.clear(clearColor, true, true, true);
  12770. // Restore state
  12771. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12772. if (curScissor === true) {
  12773. gl.enable(gl.SCISSOR_TEST);
  12774. }
  12775. else {
  12776. gl.disable(gl.SCISSOR_TEST);
  12777. }
  12778. };
  12779. /**
  12780. * Set the WebGL's viewport
  12781. * @param viewport defines the viewport element to be used
  12782. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12783. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12784. */
  12785. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12786. var width = requiredWidth || this.getRenderWidth();
  12787. var height = requiredHeight || this.getRenderHeight();
  12788. var x = viewport.x || 0;
  12789. var y = viewport.y || 0;
  12790. this._cachedViewport = viewport;
  12791. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12792. };
  12793. /**
  12794. * Directly set the WebGL Viewport
  12795. * @param x defines the x coordinate of the viewport (in screen space)
  12796. * @param y defines the y coordinate of the viewport (in screen space)
  12797. * @param width defines the width of the viewport (in screen space)
  12798. * @param height defines the height of the viewport (in screen space)
  12799. * @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
  12800. */
  12801. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12802. var currentViewport = this._cachedViewport;
  12803. this._cachedViewport = null;
  12804. this._gl.viewport(x, y, width, height);
  12805. return currentViewport;
  12806. };
  12807. /**
  12808. * Begin a new frame
  12809. */
  12810. Engine.prototype.beginFrame = function () {
  12811. this.onBeginFrameObservable.notifyObservers(this);
  12812. this._measureFps();
  12813. };
  12814. /**
  12815. * Enf the current frame
  12816. */
  12817. Engine.prototype.endFrame = function () {
  12818. // Force a flush in case we are using a bad OS.
  12819. if (this._badOS) {
  12820. this.flushFramebuffer();
  12821. }
  12822. // Submit frame to the vr device, if enabled
  12823. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12824. // TODO: We should only submit the frame if we read frameData successfully.
  12825. this._vrDisplay.submitFrame();
  12826. }
  12827. this.onEndFrameObservable.notifyObservers(this);
  12828. };
  12829. /**
  12830. * Resize the view according to the canvas' size
  12831. */
  12832. Engine.prototype.resize = function () {
  12833. // We're not resizing the size of the canvas while in VR mode & presenting
  12834. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12835. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12836. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12837. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12838. }
  12839. };
  12840. /**
  12841. * Force a specific size of the canvas
  12842. * @param width defines the new canvas' width
  12843. * @param height defines the new canvas' height
  12844. */
  12845. Engine.prototype.setSize = function (width, height) {
  12846. if (!this._renderingCanvas) {
  12847. return;
  12848. }
  12849. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12850. return;
  12851. }
  12852. this._renderingCanvas.width = width;
  12853. this._renderingCanvas.height = height;
  12854. for (var index = 0; index < this.scenes.length; index++) {
  12855. var scene = this.scenes[index];
  12856. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12857. var cam = scene.cameras[camIndex];
  12858. cam._currentRenderId = 0;
  12859. }
  12860. }
  12861. if (this.onResizeObservable.hasObservers) {
  12862. this.onResizeObservable.notifyObservers(this);
  12863. }
  12864. };
  12865. // WebVR functions
  12866. /**
  12867. * Gets a boolean indicating if a webVR device was detected
  12868. * @returns true if a webVR device was detected
  12869. */
  12870. Engine.prototype.isVRDevicePresent = function () {
  12871. return !!this._vrDisplay;
  12872. };
  12873. /**
  12874. * Gets the current webVR device
  12875. * @returns the current webVR device (or null)
  12876. */
  12877. Engine.prototype.getVRDevice = function () {
  12878. return this._vrDisplay;
  12879. };
  12880. /**
  12881. * Initializes a webVR display and starts listening to display change events
  12882. * The onVRDisplayChangedObservable will be notified upon these changes
  12883. * @returns The onVRDisplayChangedObservable
  12884. */
  12885. Engine.prototype.initWebVR = function () {
  12886. this.initWebVRAsync();
  12887. return this.onVRDisplayChangedObservable;
  12888. };
  12889. /**
  12890. * Initializes a webVR display and starts listening to display change events
  12891. * The onVRDisplayChangedObservable will be notified upon these changes
  12892. * @returns A promise containing a VRDisplay and if vr is supported
  12893. */
  12894. Engine.prototype.initWebVRAsync = function () {
  12895. var _this = this;
  12896. var notifyObservers = function () {
  12897. var eventArgs = {
  12898. vrDisplay: _this._vrDisplay,
  12899. vrSupported: _this._vrSupported
  12900. };
  12901. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12902. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12903. };
  12904. if (!this._onVrDisplayConnect) {
  12905. this._onVrDisplayConnect = function (event) {
  12906. _this._vrDisplay = event.display;
  12907. notifyObservers();
  12908. };
  12909. this._onVrDisplayDisconnect = function () {
  12910. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12911. _this._vrDisplay = undefined;
  12912. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12913. notifyObservers();
  12914. };
  12915. this._onVrDisplayPresentChange = function () {
  12916. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12917. };
  12918. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12919. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12920. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12921. }
  12922. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12923. this._webVRInitPromise.then(notifyObservers);
  12924. return this._webVRInitPromise;
  12925. };
  12926. /**
  12927. * Call this function to switch to webVR mode
  12928. * Will do nothing if webVR is not supported or if there is no webVR device
  12929. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12930. */
  12931. Engine.prototype.enableVR = function () {
  12932. var _this = this;
  12933. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12934. var onResolved = function () {
  12935. _this.onVRRequestPresentComplete.notifyObservers(true);
  12936. _this._onVRFullScreenTriggered();
  12937. };
  12938. var onRejected = function () {
  12939. _this.onVRRequestPresentComplete.notifyObservers(false);
  12940. };
  12941. this.onVRRequestPresentStart.notifyObservers(this);
  12942. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12943. }
  12944. };
  12945. /**
  12946. * Call this function to leave webVR mode
  12947. * Will do nothing if webVR is not supported or if there is no webVR device
  12948. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12949. */
  12950. Engine.prototype.disableVR = function () {
  12951. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12952. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12953. }
  12954. };
  12955. Engine.prototype._getVRDisplaysAsync = function () {
  12956. var _this = this;
  12957. return new Promise(function (res, rej) {
  12958. if (navigator.getVRDisplays) {
  12959. navigator.getVRDisplays().then(function (devices) {
  12960. _this._vrSupported = true;
  12961. // note that devices may actually be an empty array. This is fine;
  12962. // we expect this._vrDisplay to be undefined in this case.
  12963. _this._vrDisplay = devices[0];
  12964. res({
  12965. vrDisplay: _this._vrDisplay,
  12966. vrSupported: _this._vrSupported
  12967. });
  12968. });
  12969. }
  12970. else {
  12971. _this._vrDisplay = undefined;
  12972. _this._vrSupported = false;
  12973. res({
  12974. vrDisplay: _this._vrDisplay,
  12975. vrSupported: _this._vrSupported
  12976. });
  12977. }
  12978. });
  12979. };
  12980. /**
  12981. * Binds the frame buffer to the specified texture.
  12982. * @param texture The texture to render to or null for the default canvas
  12983. * @param faceIndex The face of the texture to render to in case of cube texture
  12984. * @param requiredWidth The width of the target to render to
  12985. * @param requiredHeight The height of the target to render to
  12986. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12987. * @param depthStencilTexture The depth stencil texture to use to render
  12988. */
  12989. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12990. if (this._currentRenderTarget) {
  12991. this.unBindFramebuffer(this._currentRenderTarget);
  12992. }
  12993. this._currentRenderTarget = texture;
  12994. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12995. var gl = this._gl;
  12996. if (texture.isCube) {
  12997. if (faceIndex === undefined) {
  12998. faceIndex = 0;
  12999. }
  13000. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13001. if (depthStencilTexture) {
  13002. if (depthStencilTexture._generateStencilBuffer) {
  13003. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13004. }
  13005. else {
  13006. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13007. }
  13008. }
  13009. }
  13010. if (this._cachedViewport && !forceFullscreenViewport) {
  13011. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13012. }
  13013. else {
  13014. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13015. }
  13016. this.wipeCaches();
  13017. };
  13018. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13019. if (this._currentFramebuffer !== framebuffer) {
  13020. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13021. this._currentFramebuffer = framebuffer;
  13022. }
  13023. };
  13024. /**
  13025. * Unbind the current render target texture from the webGL context
  13026. * @param texture defines the render target texture to unbind
  13027. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13028. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13029. */
  13030. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13031. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13032. this._currentRenderTarget = null;
  13033. // If MSAA, we need to bitblt back to main texture
  13034. var gl = this._gl;
  13035. if (texture._MSAAFramebuffer) {
  13036. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13037. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13038. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13039. }
  13040. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13041. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13042. gl.generateMipmap(gl.TEXTURE_2D);
  13043. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13044. }
  13045. if (onBeforeUnbind) {
  13046. if (texture._MSAAFramebuffer) {
  13047. // Bind the correct framebuffer
  13048. this.bindUnboundFramebuffer(texture._framebuffer);
  13049. }
  13050. onBeforeUnbind();
  13051. }
  13052. this.bindUnboundFramebuffer(null);
  13053. };
  13054. /**
  13055. * Unbind a list of render target textures from the webGL context
  13056. * This is used only when drawBuffer extension or webGL2 are active
  13057. * @param textures defines the render target textures to unbind
  13058. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13059. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13060. */
  13061. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13062. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13063. this._currentRenderTarget = null;
  13064. // If MSAA, we need to bitblt back to main texture
  13065. var gl = this._gl;
  13066. if (textures[0]._MSAAFramebuffer) {
  13067. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13068. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13069. var attachments = textures[0]._attachments;
  13070. if (!attachments) {
  13071. attachments = new Array(textures.length);
  13072. textures[0]._attachments = attachments;
  13073. }
  13074. for (var i = 0; i < textures.length; i++) {
  13075. var texture = textures[i];
  13076. for (var j = 0; j < attachments.length; j++) {
  13077. attachments[j] = gl.NONE;
  13078. }
  13079. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13080. gl.readBuffer(attachments[i]);
  13081. gl.drawBuffers(attachments);
  13082. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13083. }
  13084. for (var i = 0; i < attachments.length; i++) {
  13085. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13086. }
  13087. gl.drawBuffers(attachments);
  13088. }
  13089. for (var i = 0; i < textures.length; i++) {
  13090. var texture = textures[i];
  13091. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13092. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13093. gl.generateMipmap(gl.TEXTURE_2D);
  13094. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13095. }
  13096. }
  13097. if (onBeforeUnbind) {
  13098. if (textures[0]._MSAAFramebuffer) {
  13099. // Bind the correct framebuffer
  13100. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13101. }
  13102. onBeforeUnbind();
  13103. }
  13104. this.bindUnboundFramebuffer(null);
  13105. };
  13106. /**
  13107. * Force the mipmap generation for the given render target texture
  13108. * @param texture defines the render target texture to use
  13109. */
  13110. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13111. if (texture.generateMipMaps) {
  13112. var gl = this._gl;
  13113. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13114. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13115. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13116. }
  13117. };
  13118. /**
  13119. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13120. */
  13121. Engine.prototype.flushFramebuffer = function () {
  13122. this._gl.flush();
  13123. };
  13124. /**
  13125. * Unbind the current render target and bind the default framebuffer
  13126. */
  13127. Engine.prototype.restoreDefaultFramebuffer = function () {
  13128. if (this._currentRenderTarget) {
  13129. this.unBindFramebuffer(this._currentRenderTarget);
  13130. }
  13131. else {
  13132. this.bindUnboundFramebuffer(null);
  13133. }
  13134. if (this._cachedViewport) {
  13135. this.setViewport(this._cachedViewport);
  13136. }
  13137. this.wipeCaches();
  13138. };
  13139. // UBOs
  13140. /**
  13141. * Create an uniform buffer
  13142. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13143. * @param elements defines the content of the uniform buffer
  13144. * @returns the webGL uniform buffer
  13145. */
  13146. Engine.prototype.createUniformBuffer = function (elements) {
  13147. var ubo = this._gl.createBuffer();
  13148. if (!ubo) {
  13149. throw new Error("Unable to create uniform buffer");
  13150. }
  13151. this.bindUniformBuffer(ubo);
  13152. if (elements instanceof Float32Array) {
  13153. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13154. }
  13155. else {
  13156. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13157. }
  13158. this.bindUniformBuffer(null);
  13159. ubo.references = 1;
  13160. return ubo;
  13161. };
  13162. /**
  13163. * Create a dynamic uniform buffer
  13164. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13165. * @param elements defines the content of the uniform buffer
  13166. * @returns the webGL uniform buffer
  13167. */
  13168. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13169. var ubo = this._gl.createBuffer();
  13170. if (!ubo) {
  13171. throw new Error("Unable to create dynamic uniform buffer");
  13172. }
  13173. this.bindUniformBuffer(ubo);
  13174. if (elements instanceof Float32Array) {
  13175. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13176. }
  13177. else {
  13178. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13179. }
  13180. this.bindUniformBuffer(null);
  13181. ubo.references = 1;
  13182. return ubo;
  13183. };
  13184. /**
  13185. * Update an existing uniform buffer
  13186. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13187. * @param uniformBuffer defines the target uniform buffer
  13188. * @param elements defines the content to update
  13189. * @param offset defines the offset in the uniform buffer where update should start
  13190. * @param count defines the size of the data to update
  13191. */
  13192. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13193. this.bindUniformBuffer(uniformBuffer);
  13194. if (offset === undefined) {
  13195. offset = 0;
  13196. }
  13197. if (count === undefined) {
  13198. if (elements instanceof Float32Array) {
  13199. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13200. }
  13201. else {
  13202. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13203. }
  13204. }
  13205. else {
  13206. if (elements instanceof Float32Array) {
  13207. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13208. }
  13209. else {
  13210. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13211. }
  13212. }
  13213. this.bindUniformBuffer(null);
  13214. };
  13215. // VBOs
  13216. Engine.prototype._resetVertexBufferBinding = function () {
  13217. this.bindArrayBuffer(null);
  13218. this._cachedVertexBuffers = null;
  13219. };
  13220. /**
  13221. * Creates a vertex buffer
  13222. * @param data the data for the vertex buffer
  13223. * @returns the new WebGL static buffer
  13224. */
  13225. Engine.prototype.createVertexBuffer = function (data) {
  13226. var vbo = this._gl.createBuffer();
  13227. if (!vbo) {
  13228. throw new Error("Unable to create vertex buffer");
  13229. }
  13230. this.bindArrayBuffer(vbo);
  13231. if (data instanceof Array) {
  13232. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13233. }
  13234. else {
  13235. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13236. }
  13237. this._resetVertexBufferBinding();
  13238. vbo.references = 1;
  13239. return vbo;
  13240. };
  13241. /**
  13242. * Creates a dynamic vertex buffer
  13243. * @param data the data for the dynamic vertex buffer
  13244. * @returns the new WebGL dynamic buffer
  13245. */
  13246. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13247. var vbo = this._gl.createBuffer();
  13248. if (!vbo) {
  13249. throw new Error("Unable to create dynamic vertex buffer");
  13250. }
  13251. this.bindArrayBuffer(vbo);
  13252. if (data instanceof Array) {
  13253. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13254. }
  13255. else {
  13256. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13257. }
  13258. this._resetVertexBufferBinding();
  13259. vbo.references = 1;
  13260. return vbo;
  13261. };
  13262. /**
  13263. * Update a dynamic index buffer
  13264. * @param indexBuffer defines the target index buffer
  13265. * @param indices defines the data to update
  13266. * @param offset defines the offset in the target index buffer where update should start
  13267. */
  13268. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13269. if (offset === void 0) { offset = 0; }
  13270. // Force cache update
  13271. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13272. this.bindIndexBuffer(indexBuffer);
  13273. var arrayBuffer;
  13274. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13275. arrayBuffer = indices;
  13276. }
  13277. else {
  13278. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13279. }
  13280. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13281. this._resetIndexBufferBinding();
  13282. };
  13283. /**
  13284. * Updates a dynamic vertex buffer.
  13285. * @param vertexBuffer the vertex buffer to update
  13286. * @param data the data used to update the vertex buffer
  13287. * @param byteOffset the byte offset of the data
  13288. * @param byteLength the byte length of the data
  13289. */
  13290. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13291. this.bindArrayBuffer(vertexBuffer);
  13292. if (byteOffset === undefined) {
  13293. byteOffset = 0;
  13294. }
  13295. if (byteLength === undefined) {
  13296. if (data instanceof Array) {
  13297. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13298. }
  13299. else {
  13300. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13301. }
  13302. }
  13303. else {
  13304. if (data instanceof Array) {
  13305. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13306. }
  13307. else {
  13308. if (data instanceof ArrayBuffer) {
  13309. data = new Uint8Array(data, byteOffset, byteLength);
  13310. }
  13311. else {
  13312. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13313. }
  13314. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13315. }
  13316. }
  13317. this._resetVertexBufferBinding();
  13318. };
  13319. Engine.prototype._resetIndexBufferBinding = function () {
  13320. this.bindIndexBuffer(null);
  13321. this._cachedIndexBuffer = null;
  13322. };
  13323. /**
  13324. * Creates a new index buffer
  13325. * @param indices defines the content of the index buffer
  13326. * @param updatable defines if the index buffer must be updatable
  13327. * @returns a new webGL buffer
  13328. */
  13329. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13330. var vbo = this._gl.createBuffer();
  13331. if (!vbo) {
  13332. throw new Error("Unable to create index buffer");
  13333. }
  13334. this.bindIndexBuffer(vbo);
  13335. // Check for 32 bits indices
  13336. var arrayBuffer;
  13337. var need32Bits = false;
  13338. if (indices instanceof Uint16Array) {
  13339. arrayBuffer = indices;
  13340. }
  13341. else {
  13342. //check 32 bit support
  13343. if (this._caps.uintIndices) {
  13344. if (indices instanceof Uint32Array) {
  13345. arrayBuffer = indices;
  13346. need32Bits = true;
  13347. }
  13348. else {
  13349. //number[] or Int32Array, check if 32 bit is necessary
  13350. for (var index = 0; index < indices.length; index++) {
  13351. if (indices[index] > 65535) {
  13352. need32Bits = true;
  13353. break;
  13354. }
  13355. }
  13356. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13357. }
  13358. }
  13359. else {
  13360. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13361. arrayBuffer = new Uint16Array(indices);
  13362. }
  13363. }
  13364. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13365. this._resetIndexBufferBinding();
  13366. vbo.references = 1;
  13367. vbo.is32Bits = need32Bits;
  13368. return vbo;
  13369. };
  13370. /**
  13371. * Bind a webGL buffer to the webGL context
  13372. * @param buffer defines the buffer to bind
  13373. */
  13374. Engine.prototype.bindArrayBuffer = function (buffer) {
  13375. if (!this._vaoRecordInProgress) {
  13376. this._unbindVertexArrayObject();
  13377. }
  13378. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13379. };
  13380. /**
  13381. * Bind an uniform buffer to the current webGL context
  13382. * @param buffer defines the buffer to bind
  13383. */
  13384. Engine.prototype.bindUniformBuffer = function (buffer) {
  13385. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13386. };
  13387. /**
  13388. * Bind a buffer to the current webGL context at a given location
  13389. * @param buffer defines the buffer to bind
  13390. * @param location defines the index where to bind the buffer
  13391. */
  13392. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13393. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13394. };
  13395. /**
  13396. * Bind a specific block at a given index in a specific shader program
  13397. * @param shaderProgram defines the shader program
  13398. * @param blockName defines the block name
  13399. * @param index defines the index where to bind the block
  13400. */
  13401. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13402. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13403. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13404. };
  13405. ;
  13406. Engine.prototype.bindIndexBuffer = function (buffer) {
  13407. if (!this._vaoRecordInProgress) {
  13408. this._unbindVertexArrayObject();
  13409. }
  13410. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13411. };
  13412. Engine.prototype.bindBuffer = function (buffer, target) {
  13413. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13414. this._gl.bindBuffer(target, buffer);
  13415. this._currentBoundBuffer[target] = buffer;
  13416. }
  13417. };
  13418. /**
  13419. * update the bound buffer with the given data
  13420. * @param data defines the data to update
  13421. */
  13422. Engine.prototype.updateArrayBuffer = function (data) {
  13423. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13424. };
  13425. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13426. var pointer = this._currentBufferPointers[indx];
  13427. var changed = false;
  13428. if (!pointer.active) {
  13429. changed = true;
  13430. pointer.active = true;
  13431. pointer.index = indx;
  13432. pointer.size = size;
  13433. pointer.type = type;
  13434. pointer.normalized = normalized;
  13435. pointer.stride = stride;
  13436. pointer.offset = offset;
  13437. pointer.buffer = buffer;
  13438. }
  13439. else {
  13440. if (pointer.buffer !== buffer) {
  13441. pointer.buffer = buffer;
  13442. changed = true;
  13443. }
  13444. if (pointer.size !== size) {
  13445. pointer.size = size;
  13446. changed = true;
  13447. }
  13448. if (pointer.type !== type) {
  13449. pointer.type = type;
  13450. changed = true;
  13451. }
  13452. if (pointer.normalized !== normalized) {
  13453. pointer.normalized = normalized;
  13454. changed = true;
  13455. }
  13456. if (pointer.stride !== stride) {
  13457. pointer.stride = stride;
  13458. changed = true;
  13459. }
  13460. if (pointer.offset !== offset) {
  13461. pointer.offset = offset;
  13462. changed = true;
  13463. }
  13464. }
  13465. if (changed || this._vaoRecordInProgress) {
  13466. this.bindArrayBuffer(buffer);
  13467. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13468. }
  13469. };
  13470. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13471. if (indexBuffer == null) {
  13472. return;
  13473. }
  13474. if (this._cachedIndexBuffer !== indexBuffer) {
  13475. this._cachedIndexBuffer = indexBuffer;
  13476. this.bindIndexBuffer(indexBuffer);
  13477. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13478. }
  13479. };
  13480. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13481. var attributes = effect.getAttributesNames();
  13482. if (!this._vaoRecordInProgress) {
  13483. this._unbindVertexArrayObject();
  13484. }
  13485. this.unbindAllAttributes();
  13486. for (var index = 0; index < attributes.length; index++) {
  13487. var order = effect.getAttributeLocation(index);
  13488. if (order >= 0) {
  13489. var vertexBuffer = vertexBuffers[attributes[index]];
  13490. if (!vertexBuffer) {
  13491. continue;
  13492. }
  13493. this._gl.enableVertexAttribArray(order);
  13494. if (!this._vaoRecordInProgress) {
  13495. this._vertexAttribArraysEnabled[order] = true;
  13496. }
  13497. var buffer = vertexBuffer.getBuffer();
  13498. if (buffer) {
  13499. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13500. if (vertexBuffer.getIsInstanced()) {
  13501. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13502. if (!this._vaoRecordInProgress) {
  13503. this._currentInstanceLocations.push(order);
  13504. this._currentInstanceBuffers.push(buffer);
  13505. }
  13506. }
  13507. }
  13508. }
  13509. }
  13510. };
  13511. /**
  13512. * Records a vertex array object
  13513. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13514. * @param vertexBuffers defines the list of vertex buffers to store
  13515. * @param indexBuffer defines the index buffer to store
  13516. * @param effect defines the effect to store
  13517. * @returns the new vertex array object
  13518. */
  13519. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13520. var vao = this._gl.createVertexArray();
  13521. this._vaoRecordInProgress = true;
  13522. this._gl.bindVertexArray(vao);
  13523. this._mustWipeVertexAttributes = true;
  13524. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13525. this.bindIndexBuffer(indexBuffer);
  13526. this._vaoRecordInProgress = false;
  13527. this._gl.bindVertexArray(null);
  13528. return vao;
  13529. };
  13530. /**
  13531. * Bind a specific vertex array object
  13532. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13533. * @param vertexArrayObject defines the vertex array object to bind
  13534. * @param indexBuffer defines the index buffer to bind
  13535. */
  13536. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13537. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13538. this._cachedVertexArrayObject = vertexArrayObject;
  13539. this._gl.bindVertexArray(vertexArrayObject);
  13540. this._cachedVertexBuffers = null;
  13541. this._cachedIndexBuffer = null;
  13542. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13543. this._mustWipeVertexAttributes = true;
  13544. }
  13545. };
  13546. /**
  13547. * Bind webGl buffers directly to the webGL context
  13548. * @param vertexBuffer defines the vertex buffer to bind
  13549. * @param indexBuffer defines the index buffer to bind
  13550. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13551. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13552. * @param effect defines the effect associated with the vertex buffer
  13553. */
  13554. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13555. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13556. this._cachedVertexBuffers = vertexBuffer;
  13557. this._cachedEffectForVertexBuffers = effect;
  13558. var attributesCount = effect.getAttributesCount();
  13559. this._unbindVertexArrayObject();
  13560. this.unbindAllAttributes();
  13561. var offset = 0;
  13562. for (var index = 0; index < attributesCount; index++) {
  13563. if (index < vertexDeclaration.length) {
  13564. var order = effect.getAttributeLocation(index);
  13565. if (order >= 0) {
  13566. this._gl.enableVertexAttribArray(order);
  13567. this._vertexAttribArraysEnabled[order] = true;
  13568. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13569. }
  13570. offset += vertexDeclaration[index] * 4;
  13571. }
  13572. }
  13573. }
  13574. this._bindIndexBufferWithCache(indexBuffer);
  13575. };
  13576. Engine.prototype._unbindVertexArrayObject = function () {
  13577. if (!this._cachedVertexArrayObject) {
  13578. return;
  13579. }
  13580. this._cachedVertexArrayObject = null;
  13581. this._gl.bindVertexArray(null);
  13582. };
  13583. /**
  13584. * Bind a list of vertex buffers to the webGL context
  13585. * @param vertexBuffers defines the list of vertex buffers to bind
  13586. * @param indexBuffer defines the index buffer to bind
  13587. * @param effect defines the effect associated with the vertex buffers
  13588. */
  13589. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13590. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13591. this._cachedVertexBuffers = vertexBuffers;
  13592. this._cachedEffectForVertexBuffers = effect;
  13593. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13594. }
  13595. this._bindIndexBufferWithCache(indexBuffer);
  13596. };
  13597. /**
  13598. * Unbind all instance attributes
  13599. */
  13600. Engine.prototype.unbindInstanceAttributes = function () {
  13601. var boundBuffer;
  13602. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13603. var instancesBuffer = this._currentInstanceBuffers[i];
  13604. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13605. boundBuffer = instancesBuffer;
  13606. this.bindArrayBuffer(instancesBuffer);
  13607. }
  13608. var offsetLocation = this._currentInstanceLocations[i];
  13609. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13610. }
  13611. this._currentInstanceBuffers.length = 0;
  13612. this._currentInstanceLocations.length = 0;
  13613. };
  13614. /**
  13615. * Release and free the memory of a vertex array object
  13616. * @param vao defines the vertex array object to delete
  13617. */
  13618. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13619. this._gl.deleteVertexArray(vao);
  13620. };
  13621. /** @hidden */
  13622. Engine.prototype._releaseBuffer = function (buffer) {
  13623. buffer.references--;
  13624. if (buffer.references === 0) {
  13625. this._gl.deleteBuffer(buffer);
  13626. return true;
  13627. }
  13628. return false;
  13629. };
  13630. /**
  13631. * Creates a webGL buffer to use with instanciation
  13632. * @param capacity defines the size of the buffer
  13633. * @returns the webGL buffer
  13634. */
  13635. Engine.prototype.createInstancesBuffer = function (capacity) {
  13636. var buffer = this._gl.createBuffer();
  13637. if (!buffer) {
  13638. throw new Error("Unable to create instance buffer");
  13639. }
  13640. buffer.capacity = capacity;
  13641. this.bindArrayBuffer(buffer);
  13642. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13643. return buffer;
  13644. };
  13645. /**
  13646. * Delete a webGL buffer used with instanciation
  13647. * @param buffer defines the webGL buffer to delete
  13648. */
  13649. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13650. this._gl.deleteBuffer(buffer);
  13651. };
  13652. /**
  13653. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13654. * @param instancesBuffer defines the webGL buffer to update and bind
  13655. * @param data defines the data to store in the buffer
  13656. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13657. */
  13658. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13659. this.bindArrayBuffer(instancesBuffer);
  13660. if (data) {
  13661. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13662. }
  13663. if (offsetLocations[0].index !== undefined) {
  13664. var stride = 0;
  13665. for (var i = 0; i < offsetLocations.length; i++) {
  13666. var ai = offsetLocations[i];
  13667. stride += ai.attributeSize * 4;
  13668. }
  13669. for (var i = 0; i < offsetLocations.length; i++) {
  13670. var ai = offsetLocations[i];
  13671. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13672. this._gl.enableVertexAttribArray(ai.index);
  13673. this._vertexAttribArraysEnabled[ai.index] = true;
  13674. }
  13675. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13676. this._gl.vertexAttribDivisor(ai.index, 1);
  13677. this._currentInstanceLocations.push(ai.index);
  13678. this._currentInstanceBuffers.push(instancesBuffer);
  13679. }
  13680. }
  13681. else {
  13682. for (var index = 0; index < 4; index++) {
  13683. var offsetLocation = offsetLocations[index];
  13684. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13685. this._gl.enableVertexAttribArray(offsetLocation);
  13686. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13687. }
  13688. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13689. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13690. this._currentInstanceLocations.push(offsetLocation);
  13691. this._currentInstanceBuffers.push(instancesBuffer);
  13692. }
  13693. }
  13694. };
  13695. /**
  13696. * Apply all cached states (depth, culling, stencil and alpha)
  13697. */
  13698. Engine.prototype.applyStates = function () {
  13699. this._depthCullingState.apply(this._gl);
  13700. this._stencilState.apply(this._gl);
  13701. this._alphaState.apply(this._gl);
  13702. };
  13703. /**
  13704. * Send a draw order
  13705. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13706. * @param indexStart defines the starting index
  13707. * @param indexCount defines the number of index to draw
  13708. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13709. */
  13710. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13711. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13712. };
  13713. /**
  13714. * Draw a list of points
  13715. * @param verticesStart defines the index of first vertex to draw
  13716. * @param verticesCount defines the count of vertices to draw
  13717. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13718. */
  13719. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13720. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13721. };
  13722. /**
  13723. * Draw a list of unindexed primitives
  13724. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13725. * @param verticesStart defines the index of first vertex to draw
  13726. * @param verticesCount defines the count of vertices to draw
  13727. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13728. */
  13729. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13730. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13731. };
  13732. /**
  13733. * Draw a list of indexed primitives
  13734. * @param fillMode defines the primitive to use
  13735. * @param indexStart defines the starting index
  13736. * @param indexCount defines the number of index to draw
  13737. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13738. */
  13739. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13740. // Apply states
  13741. this.applyStates();
  13742. this._drawCalls.addCount(1, false);
  13743. // Render
  13744. var drawMode = this._drawMode(fillMode);
  13745. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13746. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13747. if (instancesCount) {
  13748. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13749. }
  13750. else {
  13751. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13752. }
  13753. };
  13754. /**
  13755. * Draw a list of unindexed primitives
  13756. * @param fillMode defines the primitive to use
  13757. * @param verticesStart defines the index of first vertex to draw
  13758. * @param verticesCount defines the count of vertices to draw
  13759. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13760. */
  13761. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13762. // Apply states
  13763. this.applyStates();
  13764. this._drawCalls.addCount(1, false);
  13765. var drawMode = this._drawMode(fillMode);
  13766. if (instancesCount) {
  13767. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13768. }
  13769. else {
  13770. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13771. }
  13772. };
  13773. Engine.prototype._drawMode = function (fillMode) {
  13774. switch (fillMode) {
  13775. // Triangle views
  13776. case BABYLON.Material.TriangleFillMode:
  13777. return this._gl.TRIANGLES;
  13778. case BABYLON.Material.PointFillMode:
  13779. return this._gl.POINTS;
  13780. case BABYLON.Material.WireFrameFillMode:
  13781. return this._gl.LINES;
  13782. // Draw modes
  13783. case BABYLON.Material.PointListDrawMode:
  13784. return this._gl.POINTS;
  13785. case BABYLON.Material.LineListDrawMode:
  13786. return this._gl.LINES;
  13787. case BABYLON.Material.LineLoopDrawMode:
  13788. return this._gl.LINE_LOOP;
  13789. case BABYLON.Material.LineStripDrawMode:
  13790. return this._gl.LINE_STRIP;
  13791. case BABYLON.Material.TriangleStripDrawMode:
  13792. return this._gl.TRIANGLE_STRIP;
  13793. case BABYLON.Material.TriangleFanDrawMode:
  13794. return this._gl.TRIANGLE_FAN;
  13795. default:
  13796. return this._gl.TRIANGLES;
  13797. }
  13798. };
  13799. // Shaders
  13800. /** @hidden */
  13801. Engine.prototype._releaseEffect = function (effect) {
  13802. if (this._compiledEffects[effect._key]) {
  13803. delete this._compiledEffects[effect._key];
  13804. this._deleteProgram(effect.getProgram());
  13805. }
  13806. };
  13807. /** @hidden */
  13808. Engine.prototype._deleteProgram = function (program) {
  13809. if (program) {
  13810. program.__SPECTOR_rebuildProgram = null;
  13811. if (program.transformFeedback) {
  13812. this.deleteTransformFeedback(program.transformFeedback);
  13813. program.transformFeedback = null;
  13814. }
  13815. this._gl.deleteProgram(program);
  13816. }
  13817. };
  13818. /**
  13819. * Create a new effect (used to store vertex/fragment shaders)
  13820. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13821. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13822. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13823. * @param samplers defines an array of string used to represent textures
  13824. * @param defines defines the string containing the defines to use to compile the shaders
  13825. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13826. * @param onCompiled defines a function to call when the effect creation is successful
  13827. * @param onError defines a function to call when the effect creation has failed
  13828. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13829. * @returns the new Effect
  13830. */
  13831. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13832. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13833. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13834. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13835. if (this._compiledEffects[name]) {
  13836. var compiledEffect = this._compiledEffects[name];
  13837. if (onCompiled && compiledEffect.isReady()) {
  13838. onCompiled(compiledEffect);
  13839. }
  13840. return compiledEffect;
  13841. }
  13842. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13843. effect._key = name;
  13844. this._compiledEffects[name] = effect;
  13845. return effect;
  13846. };
  13847. /**
  13848. * Create an effect to use with particle systems
  13849. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13850. * @param uniformsNames defines a list of attribute names
  13851. * @param samplers defines an array of string used to represent textures
  13852. * @param defines defines the string containing the defines to use to compile the shaders
  13853. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13854. * @param onCompiled defines a function to call when the effect creation is successful
  13855. * @param onError defines a function to call when the effect creation has failed
  13856. * @returns the new Effect
  13857. */
  13858. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13859. if (uniformsNames === void 0) { uniformsNames = []; }
  13860. if (samplers === void 0) { samplers = []; }
  13861. if (defines === void 0) { defines = ""; }
  13862. return this.createEffect({
  13863. vertex: "particles",
  13864. fragmentElement: fragmentName
  13865. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13866. };
  13867. /**
  13868. * Directly creates a webGL program
  13869. * @param vertexCode defines the vertex shader code to use
  13870. * @param fragmentCode defines the fragment shader code to use
  13871. * @param context defines the webGL context to use (if not set, the current one will be used)
  13872. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13873. * @returns the new webGL program
  13874. */
  13875. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13876. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13877. context = context || this._gl;
  13878. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13879. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13880. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13881. };
  13882. /**
  13883. * Creates a webGL program
  13884. * @param vertexCode defines the vertex shader code to use
  13885. * @param fragmentCode defines the fragment shader code to use
  13886. * @param defines defines the string containing the defines to use to compile the shaders
  13887. * @param context defines the webGL context to use (if not set, the current one will be used)
  13888. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13889. * @returns the new webGL program
  13890. */
  13891. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13892. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13893. context = context || this._gl;
  13894. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13895. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13896. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13897. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13898. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13899. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13900. return program;
  13901. };
  13902. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13903. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13904. var shaderProgram = context.createProgram();
  13905. if (!shaderProgram) {
  13906. throw new Error("Unable to create program");
  13907. }
  13908. context.attachShader(shaderProgram, vertexShader);
  13909. context.attachShader(shaderProgram, fragmentShader);
  13910. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13911. var transformFeedback = this.createTransformFeedback();
  13912. this.bindTransformFeedback(transformFeedback);
  13913. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13914. shaderProgram.transformFeedback = transformFeedback;
  13915. }
  13916. context.linkProgram(shaderProgram);
  13917. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13918. this.bindTransformFeedback(null);
  13919. }
  13920. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13921. if (!linked) {
  13922. context.validateProgram(shaderProgram);
  13923. var error = context.getProgramInfoLog(shaderProgram);
  13924. if (error) {
  13925. throw new Error(error);
  13926. }
  13927. }
  13928. context.deleteShader(vertexShader);
  13929. context.deleteShader(fragmentShader);
  13930. return shaderProgram;
  13931. };
  13932. /**
  13933. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13934. * @param shaderProgram defines the webGL program to use
  13935. * @param uniformsNames defines the list of uniform names
  13936. * @returns an array of webGL uniform locations
  13937. */
  13938. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13939. var results = new Array();
  13940. for (var index = 0; index < uniformsNames.length; index++) {
  13941. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13942. }
  13943. return results;
  13944. };
  13945. /**
  13946. * Gets the lsit of active attributes for a given webGL program
  13947. * @param shaderProgram defines the webGL program to use
  13948. * @param attributesNames defines the list of attribute names to get
  13949. * @returns an array of indices indicating the offset of each attribute
  13950. */
  13951. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13952. var results = [];
  13953. for (var index = 0; index < attributesNames.length; index++) {
  13954. try {
  13955. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13956. }
  13957. catch (e) {
  13958. results.push(-1);
  13959. }
  13960. }
  13961. return results;
  13962. };
  13963. /**
  13964. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13965. * @param effect defines the effect to activate
  13966. */
  13967. Engine.prototype.enableEffect = function (effect) {
  13968. if (!effect) {
  13969. return;
  13970. }
  13971. // Use program
  13972. this.bindSamplers(effect);
  13973. this._currentEffect = effect;
  13974. if (effect.onBind) {
  13975. effect.onBind(effect);
  13976. }
  13977. effect.onBindObservable.notifyObservers(effect);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to an array of int32
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param array defines the array of int32 to store
  13983. */
  13984. Engine.prototype.setIntArray = function (uniform, array) {
  13985. if (!uniform)
  13986. return;
  13987. this._gl.uniform1iv(uniform, array);
  13988. };
  13989. /**
  13990. * Set the value of an uniform to an array of int32 (stored as vec2)
  13991. * @param uniform defines the webGL uniform location where to store the value
  13992. * @param array defines the array of int32 to store
  13993. */
  13994. Engine.prototype.setIntArray2 = function (uniform, array) {
  13995. if (!uniform || array.length % 2 !== 0)
  13996. return;
  13997. this._gl.uniform2iv(uniform, array);
  13998. };
  13999. /**
  14000. * Set the value of an uniform to an array of int32 (stored as vec3)
  14001. * @param uniform defines the webGL uniform location where to store the value
  14002. * @param array defines the array of int32 to store
  14003. */
  14004. Engine.prototype.setIntArray3 = function (uniform, array) {
  14005. if (!uniform || array.length % 3 !== 0)
  14006. return;
  14007. this._gl.uniform3iv(uniform, array);
  14008. };
  14009. /**
  14010. * Set the value of an uniform to an array of int32 (stored as vec4)
  14011. * @param uniform defines the webGL uniform location where to store the value
  14012. * @param array defines the array of int32 to store
  14013. */
  14014. Engine.prototype.setIntArray4 = function (uniform, array) {
  14015. if (!uniform || array.length % 4 !== 0)
  14016. return;
  14017. this._gl.uniform4iv(uniform, array);
  14018. };
  14019. /**
  14020. * Set the value of an uniform to an array of float32
  14021. * @param uniform defines the webGL uniform location where to store the value
  14022. * @param array defines the array of float32 to store
  14023. */
  14024. Engine.prototype.setFloatArray = function (uniform, array) {
  14025. if (!uniform)
  14026. return;
  14027. this._gl.uniform1fv(uniform, array);
  14028. };
  14029. /**
  14030. * Set the value of an uniform to an array of float32 (stored as vec2)
  14031. * @param uniform defines the webGL uniform location where to store the value
  14032. * @param array defines the array of float32 to store
  14033. */
  14034. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14035. if (!uniform || array.length % 2 !== 0)
  14036. return;
  14037. this._gl.uniform2fv(uniform, array);
  14038. };
  14039. /**
  14040. * Set the value of an uniform to an array of float32 (stored as vec3)
  14041. * @param uniform defines the webGL uniform location where to store the value
  14042. * @param array defines the array of float32 to store
  14043. */
  14044. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14045. if (!uniform || array.length % 3 !== 0)
  14046. return;
  14047. this._gl.uniform3fv(uniform, array);
  14048. };
  14049. /**
  14050. * Set the value of an uniform to an array of float32 (stored as vec4)
  14051. * @param uniform defines the webGL uniform location where to store the value
  14052. * @param array defines the array of float32 to store
  14053. */
  14054. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14055. if (!uniform || array.length % 4 !== 0)
  14056. return;
  14057. this._gl.uniform4fv(uniform, array);
  14058. };
  14059. /**
  14060. * Set the value of an uniform to an array of number
  14061. * @param uniform defines the webGL uniform location where to store the value
  14062. * @param array defines the array of number to store
  14063. */
  14064. Engine.prototype.setArray = function (uniform, array) {
  14065. if (!uniform)
  14066. return;
  14067. this._gl.uniform1fv(uniform, array);
  14068. };
  14069. /**
  14070. * Set the value of an uniform to an array of number (stored as vec2)
  14071. * @param uniform defines the webGL uniform location where to store the value
  14072. * @param array defines the array of number to store
  14073. */
  14074. Engine.prototype.setArray2 = function (uniform, array) {
  14075. if (!uniform || array.length % 2 !== 0)
  14076. return;
  14077. this._gl.uniform2fv(uniform, array);
  14078. };
  14079. /**
  14080. * Set the value of an uniform to an array of number (stored as vec3)
  14081. * @param uniform defines the webGL uniform location where to store the value
  14082. * @param array defines the array of number to store
  14083. */
  14084. Engine.prototype.setArray3 = function (uniform, array) {
  14085. if (!uniform || array.length % 3 !== 0)
  14086. return;
  14087. this._gl.uniform3fv(uniform, array);
  14088. };
  14089. /**
  14090. * Set the value of an uniform to an array of number (stored as vec4)
  14091. * @param uniform defines the webGL uniform location where to store the value
  14092. * @param array defines the array of number to store
  14093. */
  14094. Engine.prototype.setArray4 = function (uniform, array) {
  14095. if (!uniform || array.length % 4 !== 0)
  14096. return;
  14097. this._gl.uniform4fv(uniform, array);
  14098. };
  14099. /**
  14100. * Set the value of an uniform to an array of float32 (stored as matrices)
  14101. * @param uniform defines the webGL uniform location where to store the value
  14102. * @param matrices defines the array of float32 to store
  14103. */
  14104. Engine.prototype.setMatrices = function (uniform, matrices) {
  14105. if (!uniform)
  14106. return;
  14107. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14108. };
  14109. /**
  14110. * Set the value of an uniform to a matrix
  14111. * @param uniform defines the webGL uniform location where to store the value
  14112. * @param matrix defines the matrix to store
  14113. */
  14114. Engine.prototype.setMatrix = function (uniform, matrix) {
  14115. if (!uniform)
  14116. return;
  14117. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14118. };
  14119. /**
  14120. * Set the value of an uniform to a matrix (3x3)
  14121. * @param uniform defines the webGL uniform location where to store the value
  14122. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14123. */
  14124. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14125. if (!uniform)
  14126. return;
  14127. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14128. };
  14129. /**
  14130. * Set the value of an uniform to a matrix (2x2)
  14131. * @param uniform defines the webGL uniform location where to store the value
  14132. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14133. */
  14134. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a number (int)
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param value defines the int number to store
  14143. */
  14144. Engine.prototype.setInt = function (uniform, value) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniform1i(uniform, value);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a number (float)
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param value defines the float number to store
  14153. */
  14154. Engine.prototype.setFloat = function (uniform, value) {
  14155. if (!uniform)
  14156. return;
  14157. this._gl.uniform1f(uniform, value);
  14158. };
  14159. /**
  14160. * Set the value of an uniform to a vec2
  14161. * @param uniform defines the webGL uniform location where to store the value
  14162. * @param x defines the 1st component of the value
  14163. * @param y defines the 2nd component of the value
  14164. */
  14165. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14166. if (!uniform)
  14167. return;
  14168. this._gl.uniform2f(uniform, x, y);
  14169. };
  14170. /**
  14171. * Set the value of an uniform to a vec3
  14172. * @param uniform defines the webGL uniform location where to store the value
  14173. * @param x defines the 1st component of the value
  14174. * @param y defines the 2nd component of the value
  14175. * @param z defines the 3rd component of the value
  14176. */
  14177. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14178. if (!uniform)
  14179. return;
  14180. this._gl.uniform3f(uniform, x, y, z);
  14181. };
  14182. /**
  14183. * Set the value of an uniform to a boolean
  14184. * @param uniform defines the webGL uniform location where to store the value
  14185. * @param bool defines the boolean to store
  14186. */
  14187. Engine.prototype.setBool = function (uniform, bool) {
  14188. if (!uniform)
  14189. return;
  14190. this._gl.uniform1i(uniform, bool);
  14191. };
  14192. /**
  14193. * Set the value of an uniform to a vec4
  14194. * @param uniform defines the webGL uniform location where to store the value
  14195. * @param x defines the 1st component of the value
  14196. * @param y defines the 2nd component of the value
  14197. * @param z defines the 3rd component of the value
  14198. * @param w defines the 4th component of the value
  14199. */
  14200. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniform4f(uniform, x, y, z, w);
  14204. };
  14205. /**
  14206. * Set the value of an uniform to a Color3
  14207. * @param uniform defines the webGL uniform location where to store the value
  14208. * @param color3 defines the color to store
  14209. */
  14210. Engine.prototype.setColor3 = function (uniform, color3) {
  14211. if (!uniform)
  14212. return;
  14213. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14214. };
  14215. /**
  14216. * Set the value of an uniform to a Color3 and an alpha value
  14217. * @param uniform defines the webGL uniform location where to store the value
  14218. * @param color3 defines the color to store
  14219. * @param alpha defines the alpha component to store
  14220. */
  14221. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14222. if (!uniform)
  14223. return;
  14224. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14225. };
  14226. /**
  14227. * Sets a Color4 on a uniform variable
  14228. * @param uniform defines the uniform location
  14229. * @param color4 defines the value to be set
  14230. */
  14231. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14232. if (!uniform)
  14233. return;
  14234. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14235. };
  14236. // States
  14237. /**
  14238. * Set various states to the webGL context
  14239. * @param culling defines backface culling state
  14240. * @param zOffset defines the value to apply to zOffset (0 by default)
  14241. * @param force defines if states must be applied even if cache is up to date
  14242. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14243. */
  14244. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14245. if (zOffset === void 0) { zOffset = 0; }
  14246. if (reverseSide === void 0) { reverseSide = false; }
  14247. // Culling
  14248. if (this._depthCullingState.cull !== culling || force) {
  14249. this._depthCullingState.cull = culling;
  14250. }
  14251. // Cull face
  14252. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14253. if (this._depthCullingState.cullFace !== cullFace || force) {
  14254. this._depthCullingState.cullFace = cullFace;
  14255. }
  14256. // Z offset
  14257. this.setZOffset(zOffset);
  14258. // Front face
  14259. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14260. if (this._depthCullingState.frontFace !== frontFace || force) {
  14261. this._depthCullingState.frontFace = frontFace;
  14262. }
  14263. };
  14264. /**
  14265. * Set the z offset to apply to current rendering
  14266. * @param value defines the offset to apply
  14267. */
  14268. Engine.prototype.setZOffset = function (value) {
  14269. this._depthCullingState.zOffset = value;
  14270. };
  14271. /**
  14272. * Gets the current value of the zOffset
  14273. * @returns the current zOffset state
  14274. */
  14275. Engine.prototype.getZOffset = function () {
  14276. return this._depthCullingState.zOffset;
  14277. };
  14278. /**
  14279. * Enable or disable depth buffering
  14280. * @param enable defines the state to set
  14281. */
  14282. Engine.prototype.setDepthBuffer = function (enable) {
  14283. this._depthCullingState.depthTest = enable;
  14284. };
  14285. /**
  14286. * Gets a boolean indicating if depth writing is enabled
  14287. * @returns the current depth writing state
  14288. */
  14289. Engine.prototype.getDepthWrite = function () {
  14290. return this._depthCullingState.depthMask;
  14291. };
  14292. /**
  14293. * Enable or disable depth writing
  14294. * @param enable defines the state to set
  14295. */
  14296. Engine.prototype.setDepthWrite = function (enable) {
  14297. this._depthCullingState.depthMask = enable;
  14298. };
  14299. /**
  14300. * Enable or disable color writing
  14301. * @param enable defines the state to set
  14302. */
  14303. Engine.prototype.setColorWrite = function (enable) {
  14304. this._gl.colorMask(enable, enable, enable, enable);
  14305. this._colorWrite = enable;
  14306. };
  14307. /**
  14308. * Gets a boolean indicating if color writing is enabled
  14309. * @returns the current color writing state
  14310. */
  14311. Engine.prototype.getColorWrite = function () {
  14312. return this._colorWrite;
  14313. };
  14314. /**
  14315. * Sets alpha constants used by some alpha blending modes
  14316. * @param r defines the red component
  14317. * @param g defines the green component
  14318. * @param b defines the blue component
  14319. * @param a defines the alpha component
  14320. */
  14321. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14322. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14323. };
  14324. /**
  14325. * Sets the current alpha mode
  14326. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14327. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14328. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14329. */
  14330. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14331. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14332. if (this._alphaMode === mode) {
  14333. return;
  14334. }
  14335. switch (mode) {
  14336. case Engine.ALPHA_DISABLE:
  14337. this._alphaState.alphaBlend = false;
  14338. break;
  14339. case Engine.ALPHA_PREMULTIPLIED:
  14340. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14341. this._alphaState.alphaBlend = true;
  14342. break;
  14343. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14344. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14345. this._alphaState.alphaBlend = true;
  14346. break;
  14347. case Engine.ALPHA_COMBINE:
  14348. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14349. this._alphaState.alphaBlend = true;
  14350. break;
  14351. case Engine.ALPHA_ONEONE:
  14352. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14353. this._alphaState.alphaBlend = true;
  14354. break;
  14355. case Engine.ALPHA_ADD:
  14356. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14357. this._alphaState.alphaBlend = true;
  14358. break;
  14359. case Engine.ALPHA_SUBTRACT:
  14360. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14361. this._alphaState.alphaBlend = true;
  14362. break;
  14363. case Engine.ALPHA_MULTIPLY:
  14364. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14365. this._alphaState.alphaBlend = true;
  14366. break;
  14367. case Engine.ALPHA_MAXIMIZED:
  14368. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14369. this._alphaState.alphaBlend = true;
  14370. break;
  14371. case Engine.ALPHA_INTERPOLATE:
  14372. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14373. this._alphaState.alphaBlend = true;
  14374. break;
  14375. case Engine.ALPHA_SCREENMODE:
  14376. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14377. this._alphaState.alphaBlend = true;
  14378. break;
  14379. }
  14380. if (!noDepthWriteChange) {
  14381. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14382. }
  14383. this._alphaMode = mode;
  14384. };
  14385. /**
  14386. * Gets the current alpha mode
  14387. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14388. * @returns the current alpha mode
  14389. */
  14390. Engine.prototype.getAlphaMode = function () {
  14391. return this._alphaMode;
  14392. };
  14393. // Textures
  14394. /**
  14395. * Force the entire cache to be cleared
  14396. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14397. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14398. */
  14399. Engine.prototype.wipeCaches = function (bruteForce) {
  14400. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14401. return;
  14402. }
  14403. this._currentEffect = null;
  14404. if (bruteForce) {
  14405. this.resetTextureCache();
  14406. this._currentProgram = null;
  14407. this._stencilState.reset();
  14408. this._depthCullingState.reset();
  14409. this.setDepthFunctionToLessOrEqual();
  14410. this._alphaState.reset();
  14411. }
  14412. this._resetVertexBufferBinding();
  14413. this._cachedIndexBuffer = null;
  14414. this._cachedEffectForVertexBuffers = null;
  14415. this._unbindVertexArrayObject();
  14416. this.bindIndexBuffer(null);
  14417. };
  14418. /**
  14419. * Set the compressed texture format to use, based on the formats you have, and the formats
  14420. * supported by the hardware / browser.
  14421. *
  14422. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14423. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14424. * to API arguments needed to compressed textures. This puts the burden on the container
  14425. * generator to house the arcane code for determining these for current & future formats.
  14426. *
  14427. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14428. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14429. *
  14430. * Note: The result of this call is not taken into account when a texture is base64.
  14431. *
  14432. * @param formatsAvailable defines the list of those format families you have created
  14433. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14434. *
  14435. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14436. * @returns The extension selected.
  14437. */
  14438. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14439. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14440. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14441. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14442. return this._textureFormatInUse = this._texturesSupported[i];
  14443. }
  14444. }
  14445. }
  14446. // actively set format to nothing, to allow this to be called more than once
  14447. // and possibly fail the 2nd time
  14448. this._textureFormatInUse = null;
  14449. return null;
  14450. };
  14451. /** @hidden */
  14452. Engine.prototype._createTexture = function () {
  14453. var texture = this._gl.createTexture();
  14454. if (!texture) {
  14455. throw new Error("Unable to create texture");
  14456. }
  14457. return texture;
  14458. };
  14459. /**
  14460. * Usually called from BABYLON.Texture.ts.
  14461. * Passed information to create a WebGLTexture
  14462. * @param urlArg defines a value which contains one of the following:
  14463. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14464. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14465. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14466. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14467. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14468. * @param scene needed for loading to the correct scene
  14469. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14470. * @param onLoad optional callback to be called upon successful completion
  14471. * @param onError optional callback to be called upon failure
  14472. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14473. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14474. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14475. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14476. */
  14477. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14478. var _this = this;
  14479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14480. if (onLoad === void 0) { onLoad = null; }
  14481. if (onError === void 0) { onError = null; }
  14482. if (buffer === void 0) { buffer = null; }
  14483. if (fallback === void 0) { fallback = null; }
  14484. if (format === void 0) { format = null; }
  14485. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14486. var fromData = url.substr(0, 5) === "data:";
  14487. var fromBlob = url.substr(0, 5) === "blob:";
  14488. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14489. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14490. // establish the file extension, if possible
  14491. var lastDot = url.lastIndexOf('.');
  14492. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14493. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14494. var isTGA = (extension.indexOf(".tga") === 0);
  14495. // determine if a ktx file should be substituted
  14496. var isKTX = false;
  14497. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14498. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14499. isKTX = true;
  14500. }
  14501. if (scene) {
  14502. scene._addPendingData(texture);
  14503. }
  14504. texture.url = url;
  14505. texture.generateMipMaps = !noMipmap;
  14506. texture.samplingMode = samplingMode;
  14507. texture.invertY = invertY;
  14508. if (!this._doNotHandleContextLost) {
  14509. // Keep a link to the buffer only if we plan to handle context lost
  14510. texture._buffer = buffer;
  14511. }
  14512. var onLoadObserver = null;
  14513. if (onLoad && !fallback) {
  14514. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14515. }
  14516. if (!fallback)
  14517. this._internalTexturesCache.push(texture);
  14518. var onerror = function (message, exception) {
  14519. if (scene) {
  14520. scene._removePendingData(texture);
  14521. }
  14522. if (onLoadObserver) {
  14523. texture.onLoadedObservable.remove(onLoadObserver);
  14524. }
  14525. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14526. if (isKTX) {
  14527. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14528. }
  14529. else if (BABYLON.Tools.UseFallbackTexture) {
  14530. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14531. }
  14532. if (onError) {
  14533. onError(message || "Unknown error", exception);
  14534. }
  14535. };
  14536. var callback = null;
  14537. // processing for non-image formats
  14538. if (isKTX || isTGA || isDDS) {
  14539. if (isKTX) {
  14540. callback = function (data) {
  14541. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14542. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14543. ktx.uploadLevels(_this._gl, !noMipmap);
  14544. return false;
  14545. }, samplingMode);
  14546. };
  14547. }
  14548. else if (isTGA) {
  14549. callback = function (arrayBuffer) {
  14550. var data = new Uint8Array(arrayBuffer);
  14551. var header = BABYLON.TGATools.GetTGAHeader(data);
  14552. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14553. BABYLON.TGATools.UploadContent(_this._gl, data);
  14554. return false;
  14555. }, samplingMode);
  14556. };
  14557. }
  14558. else if (isDDS) {
  14559. callback = function (data) {
  14560. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14561. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14562. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14563. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14564. return false;
  14565. }, samplingMode);
  14566. };
  14567. }
  14568. if (!buffer) {
  14569. this._loadFile(url, function (data) {
  14570. if (callback) {
  14571. callback(data);
  14572. }
  14573. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14574. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14575. });
  14576. }
  14577. else {
  14578. if (callback) {
  14579. callback(buffer);
  14580. }
  14581. }
  14582. // image format processing
  14583. }
  14584. else {
  14585. var onload = function (img) {
  14586. if (fromBlob && !_this._doNotHandleContextLost) {
  14587. // We need to store the image if we need to rebuild the texture
  14588. // in case of a webgl context lost
  14589. texture._buffer = img;
  14590. }
  14591. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14592. var gl = _this._gl;
  14593. var isPot = (img.width === potWidth && img.height === potHeight);
  14594. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14595. if (isPot) {
  14596. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14597. return false;
  14598. }
  14599. // Using shaders to rescale because canvas.drawImage is lossy
  14600. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14601. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14602. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14603. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14604. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14605. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14606. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14607. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14608. _this._releaseTexture(source);
  14609. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14610. continuationCallback();
  14611. });
  14612. return true;
  14613. }, samplingMode);
  14614. };
  14615. if (!fromData || isBase64)
  14616. if (buffer instanceof HTMLImageElement) {
  14617. onload(buffer);
  14618. }
  14619. else {
  14620. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14621. }
  14622. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14623. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14624. else
  14625. onload(buffer);
  14626. }
  14627. return texture;
  14628. };
  14629. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14630. var _this = this;
  14631. var rtt = this.createRenderTargetTexture({
  14632. width: destination.width,
  14633. height: destination.height,
  14634. }, {
  14635. generateMipMaps: false,
  14636. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14637. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14638. generateDepthBuffer: false,
  14639. generateStencilBuffer: false
  14640. });
  14641. if (!this._rescalePostProcess) {
  14642. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14643. }
  14644. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14645. _this._rescalePostProcess.onApply = function (effect) {
  14646. effect._bindTexture("textureSampler", source);
  14647. };
  14648. var hostingScene = scene;
  14649. if (!hostingScene) {
  14650. hostingScene = _this.scenes[_this.scenes.length - 1];
  14651. }
  14652. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14653. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14654. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14655. _this.unBindFramebuffer(rtt);
  14656. _this._releaseTexture(rtt);
  14657. if (onComplete) {
  14658. onComplete();
  14659. }
  14660. });
  14661. };
  14662. /**
  14663. * Update a raw texture
  14664. * @param texture defines the texture to update
  14665. * @param data defines the data to store in the texture
  14666. * @param format defines the format of the data
  14667. * @param invertY defines if data must be stored with Y axis inverted
  14668. * @param compression defines the compression used (null by default)
  14669. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14670. */
  14671. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14672. if (compression === void 0) { compression = null; }
  14673. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14674. if (!texture) {
  14675. return;
  14676. }
  14677. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14678. var internalFormat = this._getInternalFormat(format);
  14679. var textureType = this._getWebGLTextureType(type);
  14680. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14681. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14682. if (!this._doNotHandleContextLost) {
  14683. texture._bufferView = data;
  14684. texture.format = format;
  14685. texture.type = type;
  14686. texture.invertY = invertY;
  14687. texture._compression = compression;
  14688. }
  14689. if (texture.width % 4 !== 0) {
  14690. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14691. }
  14692. if (compression && data) {
  14693. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14694. }
  14695. else {
  14696. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14697. }
  14698. if (texture.generateMipMaps) {
  14699. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14700. }
  14701. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14702. // this.resetTextureCache();
  14703. texture.isReady = true;
  14704. };
  14705. /**
  14706. * Creates a raw texture
  14707. * @param data defines the data to store in the texture
  14708. * @param width defines the width of the texture
  14709. * @param height defines the height of the texture
  14710. * @param format defines the format of the data
  14711. * @param generateMipMaps defines if the engine should generate the mip levels
  14712. * @param invertY defines if data must be stored with Y axis inverted
  14713. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14714. * @param compression defines the compression used (null by default)
  14715. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14716. * @returns the raw texture inside an InternalTexture
  14717. */
  14718. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14719. if (compression === void 0) { compression = null; }
  14720. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14721. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14722. texture.baseWidth = width;
  14723. texture.baseHeight = height;
  14724. texture.width = width;
  14725. texture.height = height;
  14726. texture.format = format;
  14727. texture.generateMipMaps = generateMipMaps;
  14728. texture.samplingMode = samplingMode;
  14729. texture.invertY = invertY;
  14730. texture._compression = compression;
  14731. texture.type = type;
  14732. if (!this._doNotHandleContextLost) {
  14733. texture._bufferView = data;
  14734. }
  14735. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14736. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14737. // Filters
  14738. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14739. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14740. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14741. if (generateMipMaps) {
  14742. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14743. }
  14744. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14745. this._internalTexturesCache.push(texture);
  14746. return texture;
  14747. };
  14748. /**
  14749. * Creates a dynamic texture
  14750. * @param width defines the width of the texture
  14751. * @param height defines the height of the texture
  14752. * @param generateMipMaps defines if the engine should generate the mip levels
  14753. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14754. * @returns the dynamic texture inside an InternalTexture
  14755. */
  14756. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14757. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14758. texture.baseWidth = width;
  14759. texture.baseHeight = height;
  14760. if (generateMipMaps) {
  14761. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14762. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14763. }
  14764. // this.resetTextureCache();
  14765. texture.width = width;
  14766. texture.height = height;
  14767. texture.isReady = false;
  14768. texture.generateMipMaps = generateMipMaps;
  14769. texture.samplingMode = samplingMode;
  14770. this.updateTextureSamplingMode(samplingMode, texture);
  14771. this._internalTexturesCache.push(texture);
  14772. return texture;
  14773. };
  14774. /**
  14775. * Update the sampling mode of a given texture
  14776. * @param samplingMode defines the required sampling mode
  14777. * @param texture defines the texture to update
  14778. */
  14779. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14780. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14781. if (texture.isCube) {
  14782. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14783. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14784. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14785. }
  14786. else if (texture.is3D) {
  14787. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14788. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14789. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14790. }
  14791. else {
  14792. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14793. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14794. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14795. }
  14796. texture.samplingMode = samplingMode;
  14797. };
  14798. /**
  14799. * Update the content of a dynamic texture
  14800. * @param texture defines the texture to update
  14801. * @param canvas defines the canvas containing the source
  14802. * @param invertY defines if data must be stored with Y axis inverted
  14803. * @param premulAlpha defines if alpha is stored as premultiplied
  14804. * @param format defines the format of the data
  14805. */
  14806. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14807. if (premulAlpha === void 0) { premulAlpha = false; }
  14808. if (!texture) {
  14809. return;
  14810. }
  14811. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14812. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14813. if (premulAlpha) {
  14814. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14815. }
  14816. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14817. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14818. if (texture.generateMipMaps) {
  14819. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14820. }
  14821. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14822. if (premulAlpha) {
  14823. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14824. }
  14825. texture.isReady = true;
  14826. };
  14827. /**
  14828. * Update a video texture
  14829. * @param texture defines the texture to update
  14830. * @param video defines the video element to use
  14831. * @param invertY defines if data must be stored with Y axis inverted
  14832. */
  14833. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14834. if (!texture || texture._isDisabled) {
  14835. return;
  14836. }
  14837. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14838. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14839. try {
  14840. // Testing video texture support
  14841. if (this._videoTextureSupported === undefined) {
  14842. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14843. if (this._gl.getError() !== 0) {
  14844. this._videoTextureSupported = false;
  14845. }
  14846. else {
  14847. this._videoTextureSupported = true;
  14848. }
  14849. }
  14850. // Copy video through the current working canvas if video texture is not supported
  14851. if (!this._videoTextureSupported) {
  14852. if (!texture._workingCanvas) {
  14853. texture._workingCanvas = document.createElement("canvas");
  14854. var context = texture._workingCanvas.getContext("2d");
  14855. if (!context) {
  14856. throw new Error("Unable to get 2d context");
  14857. }
  14858. texture._workingContext = context;
  14859. texture._workingCanvas.width = texture.width;
  14860. texture._workingCanvas.height = texture.height;
  14861. }
  14862. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14863. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14864. }
  14865. else {
  14866. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14867. }
  14868. if (texture.generateMipMaps) {
  14869. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14870. }
  14871. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14872. // this.resetTextureCache();
  14873. texture.isReady = true;
  14874. }
  14875. catch (ex) {
  14876. // Something unexpected
  14877. // Let's disable the texture
  14878. texture._isDisabled = true;
  14879. }
  14880. };
  14881. /**
  14882. * Updates a depth texture Comparison Mode and Function.
  14883. * If the comparison Function is equal to 0, the mode will be set to none.
  14884. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14885. * @param texture The texture to set the comparison function for
  14886. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14887. */
  14888. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14889. if (this.webGLVersion === 1) {
  14890. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14891. return;
  14892. }
  14893. var gl = this._gl;
  14894. if (texture.isCube) {
  14895. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14896. if (comparisonFunction === 0) {
  14897. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14898. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14899. }
  14900. else {
  14901. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14902. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14903. }
  14904. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14905. }
  14906. else {
  14907. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14908. if (comparisonFunction === 0) {
  14909. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14910. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14911. }
  14912. else {
  14913. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14914. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14915. }
  14916. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14917. }
  14918. texture._comparisonFunction = comparisonFunction;
  14919. };
  14920. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14921. var width = size.width || size;
  14922. var height = size.height || size;
  14923. internalTexture.baseWidth = width;
  14924. internalTexture.baseHeight = height;
  14925. internalTexture.width = width;
  14926. internalTexture.height = height;
  14927. internalTexture.isReady = true;
  14928. internalTexture.samples = 1;
  14929. internalTexture.generateMipMaps = false;
  14930. internalTexture._generateDepthBuffer = true;
  14931. internalTexture._generateStencilBuffer = generateStencil;
  14932. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14933. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14934. internalTexture._comparisonFunction = comparisonFunction;
  14935. var gl = this._gl;
  14936. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14937. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14938. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14939. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14940. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14941. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14942. if (comparisonFunction === 0) {
  14943. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14944. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14945. }
  14946. else {
  14947. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14948. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14949. }
  14950. };
  14951. /**
  14952. * Creates a depth stencil texture.
  14953. * This is only available in WebGL 2 or with the depth texture extension available.
  14954. * @param size The size of face edge in the texture.
  14955. * @param options The options defining the texture.
  14956. * @returns The texture
  14957. */
  14958. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14959. if (options.isCube) {
  14960. var width = size.width || size;
  14961. return this._createDepthStencilCubeTexture(width, options);
  14962. }
  14963. else {
  14964. return this._createDepthStencilTexture(size, options);
  14965. }
  14966. };
  14967. /**
  14968. * Creates a depth stencil texture.
  14969. * This is only available in WebGL 2 or with the depth texture extension available.
  14970. * @param size The size of face edge in the texture.
  14971. * @param options The options defining the texture.
  14972. * @returns The texture
  14973. */
  14974. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14975. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14976. if (!this._caps.depthTextureExtension) {
  14977. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14978. return internalTexture;
  14979. }
  14980. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14981. var gl = this._gl;
  14982. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14983. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14984. if (this.webGLVersion > 1) {
  14985. if (internalOptions.generateStencil) {
  14986. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14987. }
  14988. else {
  14989. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14990. }
  14991. }
  14992. else {
  14993. if (internalOptions.generateStencil) {
  14994. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14995. }
  14996. else {
  14997. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14998. }
  14999. }
  15000. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15001. return internalTexture;
  15002. };
  15003. /**
  15004. * Creates a depth stencil cube texture.
  15005. * This is only available in WebGL 2.
  15006. * @param size The size of face edge in the cube texture.
  15007. * @param options The options defining the cube texture.
  15008. * @returns The cube texture
  15009. */
  15010. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15011. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15012. internalTexture.isCube = true;
  15013. if (this.webGLVersion === 1) {
  15014. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15015. return internalTexture;
  15016. }
  15017. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15018. var gl = this._gl;
  15019. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15020. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15021. // Create the depth/stencil buffer
  15022. for (var face = 0; face < 6; face++) {
  15023. if (internalOptions.generateStencil) {
  15024. 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);
  15025. }
  15026. else {
  15027. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15028. }
  15029. }
  15030. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15031. return internalTexture;
  15032. };
  15033. /**
  15034. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15035. * @param renderTarget The render target to set the frame buffer for
  15036. */
  15037. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15038. // Create the framebuffer
  15039. var internalTexture = renderTarget.getInternalTexture();
  15040. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15041. return;
  15042. }
  15043. var gl = this._gl;
  15044. var depthStencilTexture = renderTarget.depthStencilTexture;
  15045. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15046. if (depthStencilTexture.isCube) {
  15047. if (depthStencilTexture._generateStencilBuffer) {
  15048. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15049. }
  15050. else {
  15051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15052. }
  15053. }
  15054. else {
  15055. if (depthStencilTexture._generateStencilBuffer) {
  15056. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15057. }
  15058. else {
  15059. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15060. }
  15061. }
  15062. this.bindUnboundFramebuffer(null);
  15063. };
  15064. /**
  15065. * Creates a new render target texture
  15066. * @param size defines the size of the texture
  15067. * @param options defines the options used to create the texture
  15068. * @returns a new render target texture stored in an InternalTexture
  15069. */
  15070. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15071. var fullOptions = new RenderTargetCreationOptions();
  15072. if (options !== undefined && typeof options === "object") {
  15073. fullOptions.generateMipMaps = options.generateMipMaps;
  15074. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15075. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15076. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15077. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15078. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15079. }
  15080. else {
  15081. fullOptions.generateMipMaps = options;
  15082. fullOptions.generateDepthBuffer = true;
  15083. fullOptions.generateStencilBuffer = false;
  15084. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15085. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15086. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15087. }
  15088. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15089. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15090. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15091. }
  15092. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15093. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15094. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15095. }
  15096. var gl = this._gl;
  15097. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15098. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15099. var width = size.width || size;
  15100. var height = size.height || size;
  15101. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15102. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15103. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15104. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15105. }
  15106. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15107. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15108. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15109. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15110. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15111. // Create the framebuffer
  15112. var framebuffer = gl.createFramebuffer();
  15113. this.bindUnboundFramebuffer(framebuffer);
  15114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15115. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15116. if (fullOptions.generateMipMaps) {
  15117. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15118. }
  15119. // Unbind
  15120. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15121. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15122. this.bindUnboundFramebuffer(null);
  15123. texture._framebuffer = framebuffer;
  15124. texture.baseWidth = width;
  15125. texture.baseHeight = height;
  15126. texture.width = width;
  15127. texture.height = height;
  15128. texture.isReady = true;
  15129. texture.samples = 1;
  15130. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15131. texture.samplingMode = fullOptions.samplingMode;
  15132. texture.type = fullOptions.type;
  15133. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15134. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15135. // this.resetTextureCache();
  15136. this._internalTexturesCache.push(texture);
  15137. return texture;
  15138. };
  15139. /**
  15140. * Create a multi render target texture
  15141. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15142. * @param size defines the size of the texture
  15143. * @param options defines the creation options
  15144. * @returns the cube texture as an InternalTexture
  15145. */
  15146. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15147. var generateMipMaps = false;
  15148. var generateDepthBuffer = true;
  15149. var generateStencilBuffer = false;
  15150. var generateDepthTexture = false;
  15151. var textureCount = 1;
  15152. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15153. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15154. var types = new Array();
  15155. var samplingModes = new Array();
  15156. if (options !== undefined) {
  15157. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15158. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15159. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15160. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15161. textureCount = options.textureCount || 1;
  15162. if (options.types) {
  15163. types = options.types;
  15164. }
  15165. if (options.samplingModes) {
  15166. samplingModes = options.samplingModes;
  15167. }
  15168. }
  15169. var gl = this._gl;
  15170. // Create the framebuffer
  15171. var framebuffer = gl.createFramebuffer();
  15172. this.bindUnboundFramebuffer(framebuffer);
  15173. var width = size.width || size;
  15174. var height = size.height || size;
  15175. var textures = [];
  15176. var attachments = [];
  15177. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15178. for (var i = 0; i < textureCount; i++) {
  15179. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15180. var type = types[i] || defaultType;
  15181. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15182. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15183. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15184. }
  15185. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15186. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15187. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15188. }
  15189. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15190. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15191. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15192. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15193. }
  15194. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15195. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15196. textures.push(texture);
  15197. attachments.push(attachment);
  15198. gl.activeTexture(gl["TEXTURE" + i]);
  15199. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15201. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15202. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15203. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15204. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15205. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15206. if (generateMipMaps) {
  15207. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15208. }
  15209. // Unbind
  15210. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15211. texture._framebuffer = framebuffer;
  15212. texture._depthStencilBuffer = depthStencilBuffer;
  15213. texture.baseWidth = width;
  15214. texture.baseHeight = height;
  15215. texture.width = width;
  15216. texture.height = height;
  15217. texture.isReady = true;
  15218. texture.samples = 1;
  15219. texture.generateMipMaps = generateMipMaps;
  15220. texture.samplingMode = samplingMode;
  15221. texture.type = type;
  15222. texture._generateDepthBuffer = generateDepthBuffer;
  15223. texture._generateStencilBuffer = generateStencilBuffer;
  15224. texture._attachments = attachments;
  15225. this._internalTexturesCache.push(texture);
  15226. }
  15227. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15228. // Depth texture
  15229. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15230. gl.activeTexture(gl.TEXTURE0);
  15231. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15232. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15233. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15234. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15235. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15236. 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);
  15237. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15238. depthTexture._framebuffer = framebuffer;
  15239. depthTexture.baseWidth = width;
  15240. depthTexture.baseHeight = height;
  15241. depthTexture.width = width;
  15242. depthTexture.height = height;
  15243. depthTexture.isReady = true;
  15244. depthTexture.samples = 1;
  15245. depthTexture.generateMipMaps = generateMipMaps;
  15246. depthTexture.samplingMode = gl.NEAREST;
  15247. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15248. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15249. textures.push(depthTexture);
  15250. this._internalTexturesCache.push(depthTexture);
  15251. }
  15252. gl.drawBuffers(attachments);
  15253. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15254. this.bindUnboundFramebuffer(null);
  15255. this.resetTextureCache();
  15256. return textures;
  15257. };
  15258. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15259. if (samples === void 0) { samples = 1; }
  15260. var depthStencilBuffer = null;
  15261. var gl = this._gl;
  15262. // Create the depth/stencil buffer
  15263. if (generateStencilBuffer) {
  15264. depthStencilBuffer = gl.createRenderbuffer();
  15265. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15266. if (samples > 1) {
  15267. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15268. }
  15269. else {
  15270. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15271. }
  15272. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15273. }
  15274. else if (generateDepthBuffer) {
  15275. depthStencilBuffer = gl.createRenderbuffer();
  15276. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15277. if (samples > 1) {
  15278. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15279. }
  15280. else {
  15281. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15282. }
  15283. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15284. }
  15285. return depthStencilBuffer;
  15286. };
  15287. /**
  15288. * Updates the sample count of a render target texture
  15289. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15290. * @param texture defines the texture to update
  15291. * @param samples defines the sample count to set
  15292. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15293. */
  15294. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15295. if (this.webGLVersion < 2 || !texture) {
  15296. return 1;
  15297. }
  15298. if (texture.samples === samples) {
  15299. return samples;
  15300. }
  15301. var gl = this._gl;
  15302. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15303. // Dispose previous render buffers
  15304. if (texture._depthStencilBuffer) {
  15305. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15306. texture._depthStencilBuffer = null;
  15307. }
  15308. if (texture._MSAAFramebuffer) {
  15309. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15310. texture._MSAAFramebuffer = null;
  15311. }
  15312. if (texture._MSAARenderBuffer) {
  15313. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15314. texture._MSAARenderBuffer = null;
  15315. }
  15316. if (samples > 1) {
  15317. var framebuffer = gl.createFramebuffer();
  15318. if (!framebuffer) {
  15319. throw new Error("Unable to create multi sampled framebuffer");
  15320. }
  15321. texture._MSAAFramebuffer = framebuffer;
  15322. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15323. var colorRenderbuffer = gl.createRenderbuffer();
  15324. if (!colorRenderbuffer) {
  15325. throw new Error("Unable to create multi sampled framebuffer");
  15326. }
  15327. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15328. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15329. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15330. texture._MSAARenderBuffer = colorRenderbuffer;
  15331. }
  15332. else {
  15333. this.bindUnboundFramebuffer(texture._framebuffer);
  15334. }
  15335. texture.samples = samples;
  15336. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15337. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15338. this.bindUnboundFramebuffer(null);
  15339. return samples;
  15340. };
  15341. /**
  15342. * Update the sample count for a given multiple render target texture
  15343. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15344. * @param textures defines the textures to update
  15345. * @param samples defines the sample count to set
  15346. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15347. */
  15348. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15349. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15350. return 1;
  15351. }
  15352. if (textures[0].samples === samples) {
  15353. return samples;
  15354. }
  15355. var gl = this._gl;
  15356. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15357. // Dispose previous render buffers
  15358. if (textures[0]._depthStencilBuffer) {
  15359. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15360. textures[0]._depthStencilBuffer = null;
  15361. }
  15362. if (textures[0]._MSAAFramebuffer) {
  15363. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15364. textures[0]._MSAAFramebuffer = null;
  15365. }
  15366. for (var i = 0; i < textures.length; i++) {
  15367. if (textures[i]._MSAARenderBuffer) {
  15368. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15369. textures[i]._MSAARenderBuffer = null;
  15370. }
  15371. }
  15372. if (samples > 1) {
  15373. var framebuffer = gl.createFramebuffer();
  15374. if (!framebuffer) {
  15375. throw new Error("Unable to create multi sampled framebuffer");
  15376. }
  15377. this.bindUnboundFramebuffer(framebuffer);
  15378. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15379. var attachments = [];
  15380. for (var i = 0; i < textures.length; i++) {
  15381. var texture = textures[i];
  15382. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15383. var colorRenderbuffer = gl.createRenderbuffer();
  15384. if (!colorRenderbuffer) {
  15385. throw new Error("Unable to create multi sampled framebuffer");
  15386. }
  15387. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15388. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15389. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15390. texture._MSAAFramebuffer = framebuffer;
  15391. texture._MSAARenderBuffer = colorRenderbuffer;
  15392. texture.samples = samples;
  15393. texture._depthStencilBuffer = depthStencilBuffer;
  15394. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15395. attachments.push(attachment);
  15396. }
  15397. gl.drawBuffers(attachments);
  15398. }
  15399. else {
  15400. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15401. }
  15402. this.bindUnboundFramebuffer(null);
  15403. return samples;
  15404. };
  15405. /** @hidden */
  15406. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15407. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15408. };
  15409. /** @hidden */
  15410. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15411. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15412. };
  15413. /**
  15414. * Creates a new render target cube texture
  15415. * @param size defines the size of the texture
  15416. * @param options defines the options used to create the texture
  15417. * @returns a new render target cube texture stored in an InternalTexture
  15418. */
  15419. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15420. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15421. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15422. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15423. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15424. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15425. }
  15426. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15427. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15428. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15429. }
  15430. var gl = this._gl;
  15431. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15432. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15433. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15434. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15435. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15436. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15437. }
  15438. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15439. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15440. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15441. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15442. for (var face = 0; face < 6; face++) {
  15443. 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);
  15444. }
  15445. // Create the framebuffer
  15446. var framebuffer = gl.createFramebuffer();
  15447. this.bindUnboundFramebuffer(framebuffer);
  15448. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15449. // MipMaps
  15450. if (fullOptions.generateMipMaps) {
  15451. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15452. }
  15453. // Unbind
  15454. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15455. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15456. this.bindUnboundFramebuffer(null);
  15457. texture._framebuffer = framebuffer;
  15458. texture.width = size;
  15459. texture.height = size;
  15460. texture.isReady = true;
  15461. texture.isCube = true;
  15462. texture.samples = 1;
  15463. texture.generateMipMaps = fullOptions.generateMipMaps;
  15464. texture.samplingMode = fullOptions.samplingMode;
  15465. texture.type = fullOptions.type;
  15466. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15467. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15468. this._internalTexturesCache.push(texture);
  15469. return texture;
  15470. };
  15471. /**
  15472. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15473. * @param rootUrl defines the url where the file to load is located
  15474. * @param scene defines the current scene
  15475. * @param scale defines scale to apply to the mip map selection
  15476. * @param offset defines offset to apply to the mip map selection
  15477. * @param onLoad defines an optional callback raised when the texture is loaded
  15478. * @param onError defines an optional callback raised if there is an issue to load the texture
  15479. * @param format defines the format of the data
  15480. * @param forcedExtension defines the extension to use to pick the right loader
  15481. * @returns the cube texture as an InternalTexture
  15482. */
  15483. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15484. var _this = this;
  15485. if (onLoad === void 0) { onLoad = null; }
  15486. if (onError === void 0) { onError = null; }
  15487. if (forcedExtension === void 0) { forcedExtension = null; }
  15488. var callback = function (loadData) {
  15489. if (!loadData) {
  15490. if (onLoad) {
  15491. onLoad(null);
  15492. }
  15493. return;
  15494. }
  15495. var texture = loadData.texture;
  15496. if (loadData.info.sphericalPolynomial) {
  15497. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15498. }
  15499. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15500. texture._lodGenerationScale = scale;
  15501. texture._lodGenerationOffset = offset;
  15502. if (_this._caps.textureLOD) {
  15503. // Do not add extra process if texture lod is supported.
  15504. if (onLoad) {
  15505. onLoad(texture);
  15506. }
  15507. return;
  15508. }
  15509. var mipSlices = 3;
  15510. var gl = _this._gl;
  15511. var width = loadData.width;
  15512. if (!width) {
  15513. return;
  15514. }
  15515. var textures = [];
  15516. for (var i = 0; i < mipSlices; i++) {
  15517. //compute LOD from even spacing in smoothness (matching shader calculation)
  15518. var smoothness = i / (mipSlices - 1);
  15519. var roughness = 1 - smoothness;
  15520. var minLODIndex = offset; // roughness = 0
  15521. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15522. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15523. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15524. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15525. glTextureFromLod.isCube = true;
  15526. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15530. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15531. if (loadData.isDDS) {
  15532. var info = loadData.info;
  15533. var data = loadData.data;
  15534. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15535. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15536. }
  15537. else {
  15538. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15539. }
  15540. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15541. // Wrap in a base texture for easy binding.
  15542. var lodTexture = new BABYLON.BaseTexture(scene);
  15543. lodTexture.isCube = true;
  15544. lodTexture._texture = glTextureFromLod;
  15545. glTextureFromLod.isReady = true;
  15546. textures.push(lodTexture);
  15547. }
  15548. texture._lodTextureHigh = textures[2];
  15549. texture._lodTextureMid = textures[1];
  15550. texture._lodTextureLow = textures[0];
  15551. if (onLoad) {
  15552. onLoad(texture);
  15553. }
  15554. };
  15555. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15556. };
  15557. /**
  15558. * Creates a cube texture
  15559. * @param rootUrl defines the url where the files to load is located
  15560. * @param scene defines the current scene
  15561. * @param files defines the list of files to load (1 per face)
  15562. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15563. * @param onLoad defines an optional callback raised when the texture is loaded
  15564. * @param onError defines an optional callback raised if there is an issue to load the texture
  15565. * @param format defines the format of the data
  15566. * @param forcedExtension defines the extension to use to pick the right loader
  15567. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15568. * @returns the cube texture as an InternalTexture
  15569. */
  15570. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15571. var _this = this;
  15572. if (onLoad === void 0) { onLoad = null; }
  15573. if (onError === void 0) { onError = null; }
  15574. if (forcedExtension === void 0) { forcedExtension = null; }
  15575. if (createPolynomials === void 0) { createPolynomials = false; }
  15576. var gl = this._gl;
  15577. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15578. texture.isCube = true;
  15579. texture.url = rootUrl;
  15580. texture.generateMipMaps = !noMipmap;
  15581. if (!this._doNotHandleContextLost) {
  15582. texture._extension = forcedExtension;
  15583. texture._files = files;
  15584. }
  15585. var isKTX = false;
  15586. var isDDS = false;
  15587. var lastDot = rootUrl.lastIndexOf('.');
  15588. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15589. if (this._textureFormatInUse) {
  15590. extension = this._textureFormatInUse;
  15591. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15592. isKTX = true;
  15593. }
  15594. else {
  15595. isDDS = (extension === ".dds");
  15596. }
  15597. var onerror = function (request, exception) {
  15598. if (onError && request) {
  15599. onError(request.status + " " + request.statusText, exception);
  15600. }
  15601. };
  15602. if (isKTX) {
  15603. this._loadFile(rootUrl, function (data) {
  15604. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15605. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15606. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15607. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15608. ktx.uploadLevels(_this._gl, !noMipmap);
  15609. _this.setCubeMapTextureParams(gl, loadMipmap);
  15610. texture.width = ktx.pixelWidth;
  15611. texture.height = ktx.pixelHeight;
  15612. texture.isReady = true;
  15613. }, undefined, undefined, true, onerror);
  15614. }
  15615. else if (isDDS) {
  15616. if (files && files.length === 6) {
  15617. this._cascadeLoadFiles(scene, function (imgs) {
  15618. var info;
  15619. var loadMipmap = false;
  15620. var width = 0;
  15621. for (var index = 0; index < imgs.length; index++) {
  15622. var data = imgs[index];
  15623. info = BABYLON.DDSTools.GetDDSInfo(data);
  15624. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15625. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15626. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15627. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15628. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15629. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15630. }
  15631. texture.width = info.width;
  15632. texture.height = info.height;
  15633. texture.type = info.textureType;
  15634. width = info.width;
  15635. }
  15636. _this.setCubeMapTextureParams(gl, loadMipmap);
  15637. texture.isReady = true;
  15638. if (onLoad) {
  15639. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15640. }
  15641. }, files, onError);
  15642. }
  15643. else {
  15644. this._loadFile(rootUrl, function (data) {
  15645. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15646. if (createPolynomials) {
  15647. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15648. }
  15649. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15650. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15651. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15652. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15653. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15654. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15655. }
  15656. _this.setCubeMapTextureParams(gl, loadMipmap);
  15657. texture.width = info.width;
  15658. texture.height = info.height;
  15659. texture.isReady = true;
  15660. texture.type = info.textureType;
  15661. if (onLoad) {
  15662. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15663. }
  15664. }, undefined, undefined, true, onerror);
  15665. }
  15666. }
  15667. else {
  15668. if (!files) {
  15669. throw new Error("Cannot load cubemap because files were not defined");
  15670. }
  15671. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15672. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15673. var height = width;
  15674. _this._prepareWorkingCanvas();
  15675. if (!_this._workingCanvas || !_this._workingContext) {
  15676. return;
  15677. }
  15678. _this._workingCanvas.width = width;
  15679. _this._workingCanvas.height = height;
  15680. var faces = [
  15681. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15682. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15683. ];
  15684. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15685. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15686. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15687. for (var index = 0; index < faces.length; index++) {
  15688. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15689. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15690. }
  15691. if (!noMipmap) {
  15692. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15693. }
  15694. _this.setCubeMapTextureParams(gl, !noMipmap);
  15695. texture.width = width;
  15696. texture.height = height;
  15697. texture.isReady = true;
  15698. if (format) {
  15699. texture.format = format;
  15700. }
  15701. texture.onLoadedObservable.notifyObservers(texture);
  15702. texture.onLoadedObservable.clear();
  15703. if (onLoad) {
  15704. onLoad();
  15705. }
  15706. }, files, onError);
  15707. }
  15708. this._internalTexturesCache.push(texture);
  15709. return texture;
  15710. };
  15711. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15714. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15715. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15716. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15717. // this.resetTextureCache();
  15718. };
  15719. /**
  15720. * Update a raw cube texture
  15721. * @param texture defines the texture to udpdate
  15722. * @param data defines the data to store
  15723. * @param format defines the data format
  15724. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15725. * @param invertY defines if data must be stored with Y axis inverted
  15726. * @param compression defines the compression used (null by default)
  15727. * @param level defines which level of the texture to update
  15728. */
  15729. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15730. if (compression === void 0) { compression = null; }
  15731. if (level === void 0) { level = 0; }
  15732. texture._bufferViewArray = data;
  15733. texture.format = format;
  15734. texture.type = type;
  15735. texture.invertY = invertY;
  15736. texture._compression = compression;
  15737. var gl = this._gl;
  15738. var textureType = this._getWebGLTextureType(type);
  15739. var internalFormat = this._getInternalFormat(format);
  15740. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15741. var needConversion = false;
  15742. if (internalFormat === gl.RGB) {
  15743. internalFormat = gl.RGBA;
  15744. needConversion = true;
  15745. }
  15746. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15747. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15748. if (texture.width % 4 !== 0) {
  15749. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15750. }
  15751. // Data are known to be in +X +Y +Z -X -Y -Z
  15752. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15753. var faceData = data[faceIndex];
  15754. if (compression) {
  15755. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15756. }
  15757. else {
  15758. if (needConversion) {
  15759. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15760. }
  15761. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15762. }
  15763. }
  15764. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15765. if (isPot && texture.generateMipMaps && level === 0) {
  15766. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15767. }
  15768. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15769. // this.resetTextureCache();
  15770. texture.isReady = true;
  15771. };
  15772. /**
  15773. * Creates a new raw cube texture
  15774. * @param data defines the array of data to use to create each face
  15775. * @param size defines the size of the textures
  15776. * @param format defines the format of the data
  15777. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15778. * @param generateMipMaps defines if the engine should generate the mip levels
  15779. * @param invertY defines if data must be stored with Y axis inverted
  15780. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15781. * @param compression defines the compression used (null by default)
  15782. * @returns the cube texture as an InternalTexture
  15783. */
  15784. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15785. if (compression === void 0) { compression = null; }
  15786. var gl = this._gl;
  15787. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15788. texture.isCube = true;
  15789. texture.generateMipMaps = generateMipMaps;
  15790. texture.format = format;
  15791. texture.type = type;
  15792. if (!this._doNotHandleContextLost) {
  15793. texture._bufferViewArray = data;
  15794. }
  15795. var textureType = this._getWebGLTextureType(type);
  15796. var internalFormat = this._getInternalFormat(format);
  15797. if (internalFormat === gl.RGB) {
  15798. internalFormat = gl.RGBA;
  15799. }
  15800. var width = size;
  15801. var height = width;
  15802. texture.width = width;
  15803. texture.height = height;
  15804. // Double check on POT to generate Mips.
  15805. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15806. if (!isPot) {
  15807. generateMipMaps = false;
  15808. }
  15809. // Upload data if needed. The texture won't be ready until then.
  15810. if (data) {
  15811. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15812. }
  15813. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15814. // Filters
  15815. if (data && generateMipMaps) {
  15816. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15817. }
  15818. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15821. }
  15822. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15823. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15824. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15825. }
  15826. else {
  15827. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15828. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15829. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15830. }
  15831. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15832. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15833. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15834. return texture;
  15835. };
  15836. /**
  15837. * Creates a new raw cube texture from a specified url
  15838. * @param url defines the url where the data is located
  15839. * @param scene defines the current scene
  15840. * @param size defines the size of the textures
  15841. * @param format defines the format of the data
  15842. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15843. * @param noMipmap defines if the engine should avoid generating the mip levels
  15844. * @param callback defines a callback used to extract texture data from loaded data
  15845. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15846. * @param onLoad defines a callback called when texture is loaded
  15847. * @param onError defines a callback called if there is an error
  15848. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15849. * @param invertY defines if data must be stored with Y axis inverted
  15850. * @returns the cube texture as an InternalTexture
  15851. */
  15852. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15853. var _this = this;
  15854. if (onLoad === void 0) { onLoad = null; }
  15855. if (onError === void 0) { onError = null; }
  15856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15857. if (invertY === void 0) { invertY = false; }
  15858. var gl = this._gl;
  15859. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15860. scene._addPendingData(texture);
  15861. texture.url = url;
  15862. this._internalTexturesCache.push(texture);
  15863. var onerror = function (request, exception) {
  15864. scene._removePendingData(texture);
  15865. if (onError && request) {
  15866. onError(request.status + " " + request.statusText, exception);
  15867. }
  15868. };
  15869. var internalCallback = function (data) {
  15870. var width = texture.width;
  15871. var faceDataArrays = callback(data);
  15872. if (!faceDataArrays) {
  15873. return;
  15874. }
  15875. if (mipmapGenerator) {
  15876. var textureType = _this._getWebGLTextureType(type);
  15877. var internalFormat = _this._getInternalFormat(format);
  15878. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15879. var needConversion = false;
  15880. if (internalFormat === gl.RGB) {
  15881. internalFormat = gl.RGBA;
  15882. needConversion = true;
  15883. }
  15884. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15885. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15886. var mipData = mipmapGenerator(faceDataArrays);
  15887. for (var level = 0; level < mipData.length; level++) {
  15888. var mipSize = width >> level;
  15889. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15890. var mipFaceData = mipData[level][faceIndex];
  15891. if (needConversion) {
  15892. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15893. }
  15894. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15895. }
  15896. }
  15897. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15898. }
  15899. else {
  15900. texture.generateMipMaps = !noMipmap;
  15901. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15902. }
  15903. texture.isReady = true;
  15904. // this.resetTextureCache();
  15905. scene._removePendingData(texture);
  15906. if (onLoad) {
  15907. onLoad();
  15908. }
  15909. };
  15910. this._loadFile(url, function (data) {
  15911. internalCallback(data);
  15912. }, undefined, scene.database, true, onerror);
  15913. return texture;
  15914. };
  15915. ;
  15916. /**
  15917. * Update a raw 3D texture
  15918. * @param texture defines the texture to update
  15919. * @param data defines the data to store
  15920. * @param format defines the data format
  15921. * @param invertY defines if data must be stored with Y axis inverted
  15922. * @param compression defines the used compression (can be null)
  15923. */
  15924. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15925. if (compression === void 0) { compression = null; }
  15926. var internalFormat = this._getInternalFormat(format);
  15927. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15928. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15929. if (!this._doNotHandleContextLost) {
  15930. texture._bufferView = data;
  15931. texture.format = format;
  15932. texture.invertY = invertY;
  15933. texture._compression = compression;
  15934. }
  15935. if (texture.width % 4 !== 0) {
  15936. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15937. }
  15938. if (compression && data) {
  15939. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15940. }
  15941. else {
  15942. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15943. }
  15944. if (texture.generateMipMaps) {
  15945. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15946. }
  15947. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15948. // this.resetTextureCache();
  15949. texture.isReady = true;
  15950. };
  15951. /**
  15952. * Creates a new raw 3D texture
  15953. * @param data defines the data used to create the texture
  15954. * @param width defines the width of the texture
  15955. * @param height defines the height of the texture
  15956. * @param depth defines the depth of the texture
  15957. * @param format defines the format of the texture
  15958. * @param generateMipMaps defines if the engine must generate mip levels
  15959. * @param invertY defines if data must be stored with Y axis inverted
  15960. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15961. * @param compression defines the compressed used (can be null)
  15962. * @returns a new raw 3D texture (stored in an InternalTexture)
  15963. */
  15964. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15965. if (compression === void 0) { compression = null; }
  15966. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15967. texture.baseWidth = width;
  15968. texture.baseHeight = height;
  15969. texture.baseDepth = depth;
  15970. texture.width = width;
  15971. texture.height = height;
  15972. texture.depth = depth;
  15973. texture.format = format;
  15974. texture.generateMipMaps = generateMipMaps;
  15975. texture.samplingMode = samplingMode;
  15976. texture.is3D = true;
  15977. if (!this._doNotHandleContextLost) {
  15978. texture._bufferView = data;
  15979. }
  15980. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15981. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15982. // Filters
  15983. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15984. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15985. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15986. if (generateMipMaps) {
  15987. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15988. }
  15989. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15990. this._internalTexturesCache.push(texture);
  15991. return texture;
  15992. };
  15993. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15994. var gl = this._gl;
  15995. if (!gl) {
  15996. return;
  15997. }
  15998. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15999. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16000. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16001. if (!noMipmap && !isCompressed) {
  16002. gl.generateMipmap(gl.TEXTURE_2D);
  16003. }
  16004. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16005. // this.resetTextureCache();
  16006. if (scene) {
  16007. scene._removePendingData(texture);
  16008. }
  16009. texture.onLoadedObservable.notifyObservers(texture);
  16010. texture.onLoadedObservable.clear();
  16011. };
  16012. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16013. var _this = this;
  16014. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16015. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16016. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16017. var gl = this._gl;
  16018. if (!gl) {
  16019. return;
  16020. }
  16021. if (!texture._webGLTexture) {
  16022. // this.resetTextureCache();
  16023. if (scene) {
  16024. scene._removePendingData(texture);
  16025. }
  16026. return;
  16027. }
  16028. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16029. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16030. texture.baseWidth = width;
  16031. texture.baseHeight = height;
  16032. texture.width = potWidth;
  16033. texture.height = potHeight;
  16034. texture.isReady = true;
  16035. if (processFunction(potWidth, potHeight, function () {
  16036. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16037. })) {
  16038. // Returning as texture needs extra async steps
  16039. return;
  16040. }
  16041. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16042. };
  16043. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16044. // Create new RGBA data container.
  16045. var rgbaData;
  16046. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16047. rgbaData = new Float32Array(width * height * 4);
  16048. }
  16049. else {
  16050. rgbaData = new Uint32Array(width * height * 4);
  16051. }
  16052. // Convert each pixel.
  16053. for (var x = 0; x < width; x++) {
  16054. for (var y = 0; y < height; y++) {
  16055. var index = (y * width + x) * 3;
  16056. var newIndex = (y * width + x) * 4;
  16057. // Map Old Value to new value.
  16058. rgbaData[newIndex + 0] = rgbData[index + 0];
  16059. rgbaData[newIndex + 1] = rgbData[index + 1];
  16060. rgbaData[newIndex + 2] = rgbData[index + 2];
  16061. // Add fully opaque alpha channel.
  16062. rgbaData[newIndex + 3] = 1;
  16063. }
  16064. }
  16065. return rgbaData;
  16066. };
  16067. /** @hidden */
  16068. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16069. var gl = this._gl;
  16070. if (texture._framebuffer) {
  16071. gl.deleteFramebuffer(texture._framebuffer);
  16072. texture._framebuffer = null;
  16073. }
  16074. if (texture._depthStencilBuffer) {
  16075. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16076. texture._depthStencilBuffer = null;
  16077. }
  16078. if (texture._MSAAFramebuffer) {
  16079. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16080. texture._MSAAFramebuffer = null;
  16081. }
  16082. if (texture._MSAARenderBuffer) {
  16083. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16084. texture._MSAARenderBuffer = null;
  16085. }
  16086. };
  16087. /** @hidden */
  16088. Engine.prototype._releaseTexture = function (texture) {
  16089. var gl = this._gl;
  16090. this._releaseFramebufferObjects(texture);
  16091. gl.deleteTexture(texture._webGLTexture);
  16092. // Unbind channels
  16093. this.unbindAllTextures();
  16094. var index = this._internalTexturesCache.indexOf(texture);
  16095. if (index !== -1) {
  16096. this._internalTexturesCache.splice(index, 1);
  16097. }
  16098. // Integrated fixed lod samplers.
  16099. if (texture._lodTextureHigh) {
  16100. texture._lodTextureHigh.dispose();
  16101. }
  16102. if (texture._lodTextureMid) {
  16103. texture._lodTextureMid.dispose();
  16104. }
  16105. if (texture._lodTextureLow) {
  16106. texture._lodTextureLow.dispose();
  16107. }
  16108. // Set output texture of post process to null if the texture has been released/disposed
  16109. this.scenes.forEach(function (scene) {
  16110. scene.postProcesses.forEach(function (postProcess) {
  16111. if (postProcess._outputTexture == texture) {
  16112. postProcess._outputTexture = null;
  16113. }
  16114. });
  16115. scene.cameras.forEach(function (camera) {
  16116. camera._postProcesses.forEach(function (postProcess) {
  16117. if (postProcess) {
  16118. if (postProcess._outputTexture == texture) {
  16119. postProcess._outputTexture = null;
  16120. }
  16121. }
  16122. });
  16123. });
  16124. });
  16125. };
  16126. Engine.prototype.setProgram = function (program) {
  16127. if (this._currentProgram !== program) {
  16128. this._gl.useProgram(program);
  16129. this._currentProgram = program;
  16130. }
  16131. };
  16132. /**
  16133. * Binds an effect to the webGL context
  16134. * @param effect defines the effect to bind
  16135. */
  16136. Engine.prototype.bindSamplers = function (effect) {
  16137. this.setProgram(effect.getProgram());
  16138. var samplers = effect.getSamplers();
  16139. for (var index = 0; index < samplers.length; index++) {
  16140. var uniform = effect.getUniform(samplers[index]);
  16141. if (uniform) {
  16142. this._boundUniforms[index] = uniform;
  16143. }
  16144. }
  16145. this._currentEffect = null;
  16146. };
  16147. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16148. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16149. return;
  16150. }
  16151. // Remove
  16152. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16153. // Bind last to it
  16154. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16155. // Bind to dummy
  16156. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16157. };
  16158. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16159. if (!internalTexture) {
  16160. return -1;
  16161. }
  16162. internalTexture._initialSlot = channel;
  16163. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16164. if (channel !== internalTexture._designatedSlot) {
  16165. this._textureCollisions.addCount(1, false);
  16166. }
  16167. }
  16168. else {
  16169. if (channel !== internalTexture._designatedSlot) {
  16170. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16171. return internalTexture._designatedSlot;
  16172. }
  16173. else {
  16174. // No slot for this texture, let's pick a new one (if we find a free slot)
  16175. if (this._nextFreeTextureSlots.length) {
  16176. return this._nextFreeTextureSlots[0];
  16177. }
  16178. // We need to recycle the oldest bound texture, sorry.
  16179. this._textureCollisions.addCount(1, false);
  16180. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16181. }
  16182. }
  16183. }
  16184. return channel;
  16185. };
  16186. Engine.prototype._linkTrackers = function (previous, next) {
  16187. previous.next = next;
  16188. next.previous = previous;
  16189. };
  16190. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16191. var currentSlot = internalTexture._designatedSlot;
  16192. if (currentSlot === -1) {
  16193. return -1;
  16194. }
  16195. internalTexture._designatedSlot = -1;
  16196. if (this.disableTextureBindingOptimization) {
  16197. return -1;
  16198. }
  16199. // Remove from bound list
  16200. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16201. // Free the slot
  16202. this._boundTexturesCache[currentSlot] = null;
  16203. this._nextFreeTextureSlots.push(currentSlot);
  16204. return currentSlot;
  16205. };
  16206. Engine.prototype._activateCurrentTexture = function () {
  16207. if (this._currentTextureChannel !== this._activeChannel) {
  16208. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16209. this._currentTextureChannel = this._activeChannel;
  16210. }
  16211. };
  16212. /** @hidden */
  16213. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16214. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16215. if (force === void 0) { force = false; }
  16216. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16217. this._activeChannel = texture._designatedSlot;
  16218. }
  16219. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16220. var isTextureForRendering = texture && texture._initialSlot > -1;
  16221. if (currentTextureBound !== texture || force) {
  16222. if (currentTextureBound) {
  16223. this._removeDesignatedSlot(currentTextureBound);
  16224. }
  16225. this._activateCurrentTexture();
  16226. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16227. this._boundTexturesCache[this._activeChannel] = texture;
  16228. if (texture) {
  16229. if (!this.disableTextureBindingOptimization) {
  16230. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16231. if (slotIndex > -1) {
  16232. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16233. }
  16234. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16235. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16236. }
  16237. texture._designatedSlot = this._activeChannel;
  16238. }
  16239. }
  16240. else if (forTextureDataUpdate) {
  16241. this._activateCurrentTexture();
  16242. }
  16243. if (isTextureForRendering && !forTextureDataUpdate) {
  16244. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16245. }
  16246. };
  16247. /** @hidden */
  16248. Engine.prototype._bindTexture = function (channel, texture) {
  16249. if (channel < 0) {
  16250. return;
  16251. }
  16252. if (texture) {
  16253. channel = this._getCorrectTextureChannel(channel, texture);
  16254. }
  16255. this._activeChannel = channel;
  16256. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16257. };
  16258. /**
  16259. * Sets a texture to the webGL context from a postprocess
  16260. * @param channel defines the channel to use
  16261. * @param postProcess defines the source postprocess
  16262. */
  16263. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16264. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16265. };
  16266. /**
  16267. * Binds the output of the passed in post process to the texture channel specified
  16268. * @param channel The channel the texture should be bound to
  16269. * @param postProcess The post process which's output should be bound
  16270. */
  16271. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16272. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16273. };
  16274. /**
  16275. * Unbind all textures from the webGL context
  16276. */
  16277. Engine.prototype.unbindAllTextures = function () {
  16278. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16279. this._activeChannel = channel;
  16280. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16281. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16282. if (this.webGLVersion > 1) {
  16283. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16284. }
  16285. }
  16286. };
  16287. /**
  16288. * Sets a texture to the according uniform.
  16289. * @param channel The texture channel
  16290. * @param uniform The uniform to set
  16291. * @param texture The texture to apply
  16292. */
  16293. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16294. if (channel < 0) {
  16295. return;
  16296. }
  16297. if (uniform) {
  16298. this._boundUniforms[channel] = uniform;
  16299. }
  16300. this._setTexture(channel, texture);
  16301. };
  16302. /**
  16303. * Sets a depth stencil texture from a render target to the according uniform.
  16304. * @param channel The texture channel
  16305. * @param uniform The uniform to set
  16306. * @param texture The render target texture containing the depth stencil texture to apply
  16307. */
  16308. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16309. if (channel < 0) {
  16310. return;
  16311. }
  16312. if (uniform) {
  16313. this._boundUniforms[channel] = uniform;
  16314. }
  16315. if (!texture || !texture.depthStencilTexture) {
  16316. this._setTexture(channel, null);
  16317. }
  16318. else {
  16319. this._setTexture(channel, texture, false, true);
  16320. }
  16321. };
  16322. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16323. var uniform = this._boundUniforms[sourceSlot];
  16324. if (uniform._currentState === destination) {
  16325. return;
  16326. }
  16327. this._gl.uniform1i(uniform, destination);
  16328. uniform._currentState = destination;
  16329. };
  16330. Engine.prototype._getTextureWrapMode = function (mode) {
  16331. switch (mode) {
  16332. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16333. return this._gl.REPEAT;
  16334. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16335. return this._gl.CLAMP_TO_EDGE;
  16336. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16337. return this._gl.MIRRORED_REPEAT;
  16338. }
  16339. return this._gl.REPEAT;
  16340. };
  16341. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16342. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16343. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16344. // Not ready?
  16345. if (!texture) {
  16346. if (this._boundTexturesCache[channel] != null) {
  16347. this._activeChannel = channel;
  16348. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16349. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16350. if (this.webGLVersion > 1) {
  16351. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16352. }
  16353. }
  16354. return false;
  16355. }
  16356. // Video
  16357. if (texture.video) {
  16358. this._activeChannel = channel;
  16359. texture.update();
  16360. }
  16361. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16362. texture.delayLoad();
  16363. return false;
  16364. }
  16365. var internalTexture;
  16366. if (depthStencilTexture) {
  16367. internalTexture = texture.depthStencilTexture;
  16368. }
  16369. else if (texture.isReady()) {
  16370. internalTexture = texture.getInternalTexture();
  16371. }
  16372. else if (texture.isCube) {
  16373. internalTexture = this.emptyCubeTexture;
  16374. }
  16375. else if (texture.is3D) {
  16376. internalTexture = this.emptyTexture3D;
  16377. }
  16378. else {
  16379. internalTexture = this.emptyTexture;
  16380. }
  16381. if (!isPartOfTextureArray) {
  16382. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16383. }
  16384. var needToBind = true;
  16385. if (this._boundTexturesCache[channel] === internalTexture) {
  16386. this._moveBoundTextureOnTop(internalTexture);
  16387. if (!isPartOfTextureArray) {
  16388. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16389. }
  16390. needToBind = false;
  16391. }
  16392. this._activeChannel = channel;
  16393. if (internalTexture && internalTexture.is3D) {
  16394. if (needToBind) {
  16395. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16396. }
  16397. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16398. internalTexture._cachedWrapU = texture.wrapU;
  16399. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16400. }
  16401. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16402. internalTexture._cachedWrapV = texture.wrapV;
  16403. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16404. }
  16405. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16406. internalTexture._cachedWrapR = texture.wrapR;
  16407. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16408. }
  16409. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16410. }
  16411. else if (internalTexture && internalTexture.isCube) {
  16412. if (needToBind) {
  16413. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16414. }
  16415. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16416. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16417. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16418. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16419. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16420. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16421. }
  16422. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16423. }
  16424. else {
  16425. if (needToBind) {
  16426. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16427. }
  16428. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16429. internalTexture._cachedWrapU = texture.wrapU;
  16430. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16431. }
  16432. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16433. internalTexture._cachedWrapV = texture.wrapV;
  16434. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16435. }
  16436. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16437. }
  16438. return true;
  16439. };
  16440. /**
  16441. * Sets an array of texture to the webGL context
  16442. * @param channel defines the channel where the texture array must be set
  16443. * @param uniform defines the associated uniform location
  16444. * @param textures defines the array of textures to bind
  16445. */
  16446. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16447. if (channel < 0 || !uniform) {
  16448. return;
  16449. }
  16450. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16451. this._textureUnits = new Int32Array(textures.length);
  16452. }
  16453. for (var i = 0; i < textures.length; i++) {
  16454. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16455. }
  16456. this._gl.uniform1iv(uniform, this._textureUnits);
  16457. for (var index = 0; index < textures.length; index++) {
  16458. this._setTexture(this._textureUnits[index], textures[index], true);
  16459. }
  16460. };
  16461. /** @hidden */
  16462. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16463. var internalTexture = texture.getInternalTexture();
  16464. if (!internalTexture) {
  16465. return;
  16466. }
  16467. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16468. var value = texture.anisotropicFilteringLevel;
  16469. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16470. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16471. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16472. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16473. }
  16474. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16475. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16476. internalTexture._cachedAnisotropicFilteringLevel = value;
  16477. }
  16478. };
  16479. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16480. this._bindTextureDirectly(target, texture, true, true);
  16481. this._gl.texParameterf(target, parameter, value);
  16482. };
  16483. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16484. if (texture) {
  16485. this._bindTextureDirectly(target, texture, true, true);
  16486. }
  16487. this._gl.texParameteri(target, parameter, value);
  16488. };
  16489. /**
  16490. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16491. * @param x defines the x coordinate of the rectangle where pixels must be read
  16492. * @param y defines the y coordinate of the rectangle where pixels must be read
  16493. * @param width defines the width of the rectangle where pixels must be read
  16494. * @param height defines the height of the rectangle where pixels must be read
  16495. * @returns a Uint8Array containing RGBA colors
  16496. */
  16497. Engine.prototype.readPixels = function (x, y, width, height) {
  16498. var data = new Uint8Array(height * width * 4);
  16499. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16500. return data;
  16501. };
  16502. /**
  16503. * Add an externaly attached data from its key.
  16504. * This method call will fail and return false, if such key already exists.
  16505. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16506. * @param key the unique key that identifies the data
  16507. * @param data the data object to associate to the key for this Engine instance
  16508. * @return true if no such key were already present and the data was added successfully, false otherwise
  16509. */
  16510. Engine.prototype.addExternalData = function (key, data) {
  16511. if (!this._externalData) {
  16512. this._externalData = new BABYLON.StringDictionary();
  16513. }
  16514. return this._externalData.add(key, data);
  16515. };
  16516. /**
  16517. * Get an externaly attached data from its key
  16518. * @param key the unique key that identifies the data
  16519. * @return the associated data, if present (can be null), or undefined if not present
  16520. */
  16521. Engine.prototype.getExternalData = function (key) {
  16522. if (!this._externalData) {
  16523. this._externalData = new BABYLON.StringDictionary();
  16524. }
  16525. return this._externalData.get(key);
  16526. };
  16527. /**
  16528. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16529. * @param key the unique key that identifies the data
  16530. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16531. * @return the associated data, can be null if the factory returned null.
  16532. */
  16533. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16534. if (!this._externalData) {
  16535. this._externalData = new BABYLON.StringDictionary();
  16536. }
  16537. return this._externalData.getOrAddWithFactory(key, factory);
  16538. };
  16539. /**
  16540. * Remove an externaly attached data from the Engine instance
  16541. * @param key the unique key that identifies the data
  16542. * @return true if the data was successfully removed, false if it doesn't exist
  16543. */
  16544. Engine.prototype.removeExternalData = function (key) {
  16545. if (!this._externalData) {
  16546. this._externalData = new BABYLON.StringDictionary();
  16547. }
  16548. return this._externalData.remove(key);
  16549. };
  16550. /**
  16551. * Unbind all vertex attributes from the webGL context
  16552. */
  16553. Engine.prototype.unbindAllAttributes = function () {
  16554. if (this._mustWipeVertexAttributes) {
  16555. this._mustWipeVertexAttributes = false;
  16556. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16557. this._gl.disableVertexAttribArray(i);
  16558. this._vertexAttribArraysEnabled[i] = false;
  16559. this._currentBufferPointers[i].active = false;
  16560. }
  16561. return;
  16562. }
  16563. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16564. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16565. continue;
  16566. }
  16567. this._gl.disableVertexAttribArray(i);
  16568. this._vertexAttribArraysEnabled[i] = false;
  16569. this._currentBufferPointers[i].active = false;
  16570. }
  16571. };
  16572. /**
  16573. * 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
  16574. */
  16575. Engine.prototype.releaseEffects = function () {
  16576. for (var name in this._compiledEffects) {
  16577. this._deleteProgram(this._compiledEffects[name]._program);
  16578. }
  16579. this._compiledEffects = {};
  16580. };
  16581. /**
  16582. * Dispose and release all associated resources
  16583. */
  16584. Engine.prototype.dispose = function () {
  16585. this.hideLoadingUI();
  16586. this.stopRenderLoop();
  16587. // Release postProcesses
  16588. while (this.postProcesses.length) {
  16589. this.postProcesses[0].dispose();
  16590. }
  16591. // Empty texture
  16592. if (this._emptyTexture) {
  16593. this._releaseTexture(this._emptyTexture);
  16594. this._emptyTexture = null;
  16595. }
  16596. if (this._emptyCubeTexture) {
  16597. this._releaseTexture(this._emptyCubeTexture);
  16598. this._emptyCubeTexture = null;
  16599. }
  16600. // Rescale PP
  16601. if (this._rescalePostProcess) {
  16602. this._rescalePostProcess.dispose();
  16603. }
  16604. // Release scenes
  16605. while (this.scenes.length) {
  16606. this.scenes[0].dispose();
  16607. }
  16608. // Release audio engine
  16609. if (Engine.audioEngine) {
  16610. Engine.audioEngine.dispose();
  16611. }
  16612. // Release effects
  16613. this.releaseEffects();
  16614. // Unbind
  16615. this.unbindAllAttributes();
  16616. this._boundUniforms = [];
  16617. if (this._dummyFramebuffer) {
  16618. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16619. }
  16620. //WebVR
  16621. this.disableVR();
  16622. // Events
  16623. if (BABYLON.Tools.IsWindowObjectExist()) {
  16624. window.removeEventListener("blur", this._onBlur);
  16625. window.removeEventListener("focus", this._onFocus);
  16626. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16627. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16628. if (this._renderingCanvas) {
  16629. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16630. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16631. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16632. if (!this._doNotHandleContextLost) {
  16633. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16634. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16635. }
  16636. }
  16637. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16638. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16639. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16640. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16641. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16642. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16643. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16644. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16645. if (this._onVrDisplayConnect) {
  16646. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16647. if (this._onVrDisplayDisconnect) {
  16648. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16649. }
  16650. if (this._onVrDisplayPresentChange) {
  16651. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16652. }
  16653. this._onVrDisplayConnect = null;
  16654. this._onVrDisplayDisconnect = null;
  16655. }
  16656. }
  16657. // Remove from Instances
  16658. var index = Engine.Instances.indexOf(this);
  16659. if (index >= 0) {
  16660. Engine.Instances.splice(index, 1);
  16661. }
  16662. this._workingCanvas = null;
  16663. this._workingContext = null;
  16664. this._currentBufferPointers = [];
  16665. this._renderingCanvas = null;
  16666. this._currentProgram = null;
  16667. this._bindedRenderFunction = null;
  16668. this.onResizeObservable.clear();
  16669. this.onCanvasBlurObservable.clear();
  16670. this.onCanvasFocusObservable.clear();
  16671. this.onCanvasPointerOutObservable.clear();
  16672. this.onBeginFrameObservable.clear();
  16673. this.onEndFrameObservable.clear();
  16674. BABYLON.Effect.ResetCache();
  16675. // Abort active requests
  16676. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16677. var request = _a[_i];
  16678. request.abort();
  16679. }
  16680. };
  16681. // Loading screen
  16682. /**
  16683. * Display the loading screen
  16684. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16685. */
  16686. Engine.prototype.displayLoadingUI = function () {
  16687. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16688. return;
  16689. }
  16690. var loadingScreen = this.loadingScreen;
  16691. if (loadingScreen) {
  16692. loadingScreen.displayLoadingUI();
  16693. }
  16694. };
  16695. /**
  16696. * Hide the loading screen
  16697. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16698. */
  16699. Engine.prototype.hideLoadingUI = function () {
  16700. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16701. return;
  16702. }
  16703. var loadingScreen = this.loadingScreen;
  16704. if (loadingScreen) {
  16705. loadingScreen.hideLoadingUI();
  16706. }
  16707. };
  16708. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16709. /**
  16710. * Gets the current loading screen object
  16711. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16712. */
  16713. get: function () {
  16714. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16715. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16716. return this._loadingScreen;
  16717. },
  16718. /**
  16719. * Sets the current loading screen object
  16720. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16721. */
  16722. set: function (loadingScreen) {
  16723. this._loadingScreen = loadingScreen;
  16724. },
  16725. enumerable: true,
  16726. configurable: true
  16727. });
  16728. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16729. /**
  16730. * Sets the current loading screen text
  16731. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16732. */
  16733. set: function (text) {
  16734. this.loadingScreen.loadingUIText = text;
  16735. },
  16736. enumerable: true,
  16737. configurable: true
  16738. });
  16739. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16740. /**
  16741. * Sets the current loading screen background color
  16742. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16743. */
  16744. set: function (color) {
  16745. this.loadingScreen.loadingUIBackgroundColor = color;
  16746. },
  16747. enumerable: true,
  16748. configurable: true
  16749. });
  16750. /**
  16751. * Attach a new callback raised when context lost event is fired
  16752. * @param callback defines the callback to call
  16753. */
  16754. Engine.prototype.attachContextLostEvent = function (callback) {
  16755. if (this._renderingCanvas) {
  16756. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16757. }
  16758. };
  16759. /**
  16760. * Attach a new callback raised when context restored event is fired
  16761. * @param callback defines the callback to call
  16762. */
  16763. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16764. if (this._renderingCanvas) {
  16765. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16766. }
  16767. };
  16768. /**
  16769. * Gets the source code of the vertex shader associated with a specific webGL program
  16770. * @param program defines the program to use
  16771. * @returns a string containing the source code of the vertex shader associated with the program
  16772. */
  16773. Engine.prototype.getVertexShaderSource = function (program) {
  16774. var shaders = this._gl.getAttachedShaders(program);
  16775. if (!shaders) {
  16776. return null;
  16777. }
  16778. return this._gl.getShaderSource(shaders[0]);
  16779. };
  16780. /**
  16781. * Gets the source code of the fragment shader associated with a specific webGL program
  16782. * @param program defines the program to use
  16783. * @returns a string containing the source code of the fragment shader associated with the program
  16784. */
  16785. Engine.prototype.getFragmentShaderSource = function (program) {
  16786. var shaders = this._gl.getAttachedShaders(program);
  16787. if (!shaders) {
  16788. return null;
  16789. }
  16790. return this._gl.getShaderSource(shaders[1]);
  16791. };
  16792. /**
  16793. * Get the current error code of the webGL context
  16794. * @returns the error code
  16795. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16796. */
  16797. Engine.prototype.getError = function () {
  16798. return this._gl.getError();
  16799. };
  16800. // FPS
  16801. /**
  16802. * Gets the current framerate
  16803. * @returns a number representing the framerate
  16804. */
  16805. Engine.prototype.getFps = function () {
  16806. return this._fps;
  16807. };
  16808. /**
  16809. * Gets the time spent between current and previous frame
  16810. * @returns a number representing the delta time in ms
  16811. */
  16812. Engine.prototype.getDeltaTime = function () {
  16813. return this._deltaTime;
  16814. };
  16815. Engine.prototype._measureFps = function () {
  16816. this._performanceMonitor.sampleFrame();
  16817. this._fps = this._performanceMonitor.averageFPS;
  16818. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16819. };
  16820. /** @hidden */
  16821. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16822. if (faceIndex === void 0) { faceIndex = -1; }
  16823. var gl = this._gl;
  16824. if (!this._dummyFramebuffer) {
  16825. var dummy = gl.createFramebuffer();
  16826. if (!dummy) {
  16827. throw new Error("Unable to create dummy framebuffer");
  16828. }
  16829. this._dummyFramebuffer = dummy;
  16830. }
  16831. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16832. if (faceIndex > -1) {
  16833. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16834. }
  16835. else {
  16836. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16837. }
  16838. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16839. var buffer;
  16840. switch (readType) {
  16841. case gl.UNSIGNED_BYTE:
  16842. buffer = new Uint8Array(4 * width * height);
  16843. readType = gl.UNSIGNED_BYTE;
  16844. break;
  16845. default:
  16846. buffer = new Float32Array(4 * width * height);
  16847. readType = gl.FLOAT;
  16848. break;
  16849. }
  16850. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16851. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16852. return buffer;
  16853. };
  16854. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16855. if (this._webGLVersion > 1) {
  16856. return this._caps.colorBufferFloat;
  16857. }
  16858. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16859. };
  16860. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16861. if (this._webGLVersion > 1) {
  16862. return this._caps.colorBufferFloat;
  16863. }
  16864. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16865. };
  16866. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16867. Engine.prototype._canRenderToFramebuffer = function (type) {
  16868. var gl = this._gl;
  16869. //clear existing errors
  16870. while (gl.getError() !== gl.NO_ERROR) { }
  16871. var successful = true;
  16872. var texture = gl.createTexture();
  16873. gl.bindTexture(gl.TEXTURE_2D, texture);
  16874. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16875. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16877. var fb = gl.createFramebuffer();
  16878. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16879. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16880. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16881. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16882. successful = successful && (gl.getError() === gl.NO_ERROR);
  16883. //try render by clearing frame buffer's color buffer
  16884. if (successful) {
  16885. gl.clear(gl.COLOR_BUFFER_BIT);
  16886. successful = successful && (gl.getError() === gl.NO_ERROR);
  16887. }
  16888. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16889. if (successful) {
  16890. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16891. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16892. var readFormat = gl.RGBA;
  16893. var readType = gl.UNSIGNED_BYTE;
  16894. var buffer = new Uint8Array(4);
  16895. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16896. successful = successful && (gl.getError() === gl.NO_ERROR);
  16897. }
  16898. //clean up
  16899. gl.deleteTexture(texture);
  16900. gl.deleteFramebuffer(fb);
  16901. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16902. //clear accumulated errors
  16903. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16904. return successful;
  16905. };
  16906. /** @hidden */
  16907. Engine.prototype._getWebGLTextureType = function (type) {
  16908. if (type === Engine.TEXTURETYPE_FLOAT) {
  16909. return this._gl.FLOAT;
  16910. }
  16911. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16912. // Add Half Float Constant.
  16913. return this._gl.HALF_FLOAT_OES;
  16914. }
  16915. return this._gl.UNSIGNED_BYTE;
  16916. };
  16917. ;
  16918. Engine.prototype._getInternalFormat = function (format) {
  16919. var internalFormat = this._gl.RGBA;
  16920. switch (format) {
  16921. case Engine.TEXTUREFORMAT_ALPHA:
  16922. internalFormat = this._gl.ALPHA;
  16923. break;
  16924. case Engine.TEXTUREFORMAT_LUMINANCE:
  16925. internalFormat = this._gl.LUMINANCE;
  16926. break;
  16927. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16928. internalFormat = this._gl.LUMINANCE_ALPHA;
  16929. break;
  16930. case Engine.TEXTUREFORMAT_RGB:
  16931. case Engine.TEXTUREFORMAT_RGB32F:
  16932. internalFormat = this._gl.RGB;
  16933. break;
  16934. case Engine.TEXTUREFORMAT_RGBA:
  16935. case Engine.TEXTUREFORMAT_RGBA32F:
  16936. internalFormat = this._gl.RGBA;
  16937. break;
  16938. case Engine.TEXTUREFORMAT_R32F:
  16939. internalFormat = this._gl.RED;
  16940. break;
  16941. case Engine.TEXTUREFORMAT_RG32F:
  16942. internalFormat = this._gl.RG;
  16943. break;
  16944. }
  16945. return internalFormat;
  16946. };
  16947. /** @hidden */
  16948. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16949. if (this._webGLVersion === 1) {
  16950. if (format) {
  16951. switch (format) {
  16952. case Engine.TEXTUREFORMAT_LUMINANCE:
  16953. return this._gl.LUMINANCE;
  16954. }
  16955. }
  16956. return this._gl.RGBA;
  16957. }
  16958. if (type === Engine.TEXTURETYPE_FLOAT) {
  16959. if (format) {
  16960. switch (format) {
  16961. case Engine.TEXTUREFORMAT_R32F:
  16962. return this._gl.R32F;
  16963. case Engine.TEXTUREFORMAT_RG32F:
  16964. return this._gl.RG32F;
  16965. case Engine.TEXTUREFORMAT_RGB32F:
  16966. return this._gl.RGB32F;
  16967. }
  16968. }
  16969. return this._gl.RGBA32F;
  16970. }
  16971. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16972. return this._gl.RGBA16F;
  16973. }
  16974. if (format) {
  16975. switch (format) {
  16976. case Engine.TEXTUREFORMAT_LUMINANCE:
  16977. return this._gl.LUMINANCE;
  16978. case Engine.TEXTUREFORMAT_RGB:
  16979. return this._gl.RGB;
  16980. }
  16981. }
  16982. return this._gl.RGBA;
  16983. };
  16984. ;
  16985. /** @hidden */
  16986. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16987. if (type === Engine.TEXTURETYPE_FLOAT) {
  16988. return this._gl.RGBA32F;
  16989. }
  16990. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16991. return this._gl.RGBA16F;
  16992. }
  16993. return this._gl.RGBA8;
  16994. };
  16995. ;
  16996. /**
  16997. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16998. * @return the new query
  16999. */
  17000. Engine.prototype.createQuery = function () {
  17001. return this._gl.createQuery();
  17002. };
  17003. /**
  17004. * Delete and release a webGL query
  17005. * @param query defines the query to delete
  17006. * @return the current engine
  17007. */
  17008. Engine.prototype.deleteQuery = function (query) {
  17009. this._gl.deleteQuery(query);
  17010. return this;
  17011. };
  17012. /**
  17013. * Check if a given query has resolved and got its value
  17014. * @param query defines the query to check
  17015. * @returns true if the query got its value
  17016. */
  17017. Engine.prototype.isQueryResultAvailable = function (query) {
  17018. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17019. };
  17020. /**
  17021. * Gets the value of a given query
  17022. * @param query defines the query to check
  17023. * @returns the value of the query
  17024. */
  17025. Engine.prototype.getQueryResult = function (query) {
  17026. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17027. };
  17028. /**
  17029. * Initiates an occlusion query
  17030. * @param algorithmType defines the algorithm to use
  17031. * @param query defines the query to use
  17032. * @returns the current engine
  17033. * @see http://doc.babylonjs.com/features/occlusionquery
  17034. */
  17035. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17036. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17037. this._gl.beginQuery(glAlgorithm, query);
  17038. return this;
  17039. };
  17040. /**
  17041. * Ends an occlusion query
  17042. * @see http://doc.babylonjs.com/features/occlusionquery
  17043. * @param algorithmType defines the algorithm to use
  17044. * @returns the current engine
  17045. */
  17046. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17047. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17048. this._gl.endQuery(glAlgorithm);
  17049. return this;
  17050. };
  17051. /* Time queries */
  17052. Engine.prototype._createTimeQuery = function () {
  17053. var timerQuery = this._caps.timerQuery;
  17054. if (timerQuery.createQueryEXT) {
  17055. return timerQuery.createQueryEXT();
  17056. }
  17057. return this.createQuery();
  17058. };
  17059. Engine.prototype._deleteTimeQuery = function (query) {
  17060. var timerQuery = this._caps.timerQuery;
  17061. if (timerQuery.deleteQueryEXT) {
  17062. timerQuery.deleteQueryEXT(query);
  17063. return;
  17064. }
  17065. this.deleteQuery(query);
  17066. };
  17067. Engine.prototype._getTimeQueryResult = function (query) {
  17068. var timerQuery = this._caps.timerQuery;
  17069. if (timerQuery.getQueryObjectEXT) {
  17070. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17071. }
  17072. return this.getQueryResult(query);
  17073. };
  17074. Engine.prototype._getTimeQueryAvailability = function (query) {
  17075. var timerQuery = this._caps.timerQuery;
  17076. if (timerQuery.getQueryObjectEXT) {
  17077. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17078. }
  17079. return this.isQueryResultAvailable(query);
  17080. };
  17081. /**
  17082. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17083. * Please note that only one query can be issued at a time
  17084. * @returns a time token used to track the time span
  17085. */
  17086. Engine.prototype.startTimeQuery = function () {
  17087. var timerQuery = this._caps.timerQuery;
  17088. if (!timerQuery) {
  17089. return null;
  17090. }
  17091. var token = new BABYLON._TimeToken();
  17092. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17093. if (this._caps.canUseTimestampForTimerQuery) {
  17094. token._startTimeQuery = this._createTimeQuery();
  17095. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17096. }
  17097. else {
  17098. if (this._currentNonTimestampToken) {
  17099. return this._currentNonTimestampToken;
  17100. }
  17101. token._timeElapsedQuery = this._createTimeQuery();
  17102. if (timerQuery.beginQueryEXT) {
  17103. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17104. }
  17105. else {
  17106. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17107. }
  17108. this._currentNonTimestampToken = token;
  17109. }
  17110. return token;
  17111. };
  17112. /**
  17113. * Ends a time query
  17114. * @param token defines the token used to measure the time span
  17115. * @returns the time spent (in ns)
  17116. */
  17117. Engine.prototype.endTimeQuery = function (token) {
  17118. var timerQuery = this._caps.timerQuery;
  17119. if (!timerQuery || !token) {
  17120. return -1;
  17121. }
  17122. if (this._caps.canUseTimestampForTimerQuery) {
  17123. if (!token._startTimeQuery) {
  17124. return -1;
  17125. }
  17126. if (!token._endTimeQuery) {
  17127. token._endTimeQuery = this._createTimeQuery();
  17128. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17129. }
  17130. }
  17131. else if (!token._timeElapsedQueryEnded) {
  17132. if (!token._timeElapsedQuery) {
  17133. return -1;
  17134. }
  17135. if (timerQuery.endQueryEXT) {
  17136. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17137. }
  17138. else {
  17139. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17140. }
  17141. token._timeElapsedQueryEnded = true;
  17142. }
  17143. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17144. var available = false;
  17145. if (token._endTimeQuery) {
  17146. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17147. }
  17148. else if (token._timeElapsedQuery) {
  17149. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17150. }
  17151. if (available && !disjoint) {
  17152. var result = 0;
  17153. if (this._caps.canUseTimestampForTimerQuery) {
  17154. if (!token._startTimeQuery || !token._endTimeQuery) {
  17155. return -1;
  17156. }
  17157. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17158. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17159. result = timeEnd - timeStart;
  17160. this._deleteTimeQuery(token._startTimeQuery);
  17161. this._deleteTimeQuery(token._endTimeQuery);
  17162. token._startTimeQuery = null;
  17163. token._endTimeQuery = null;
  17164. }
  17165. else {
  17166. if (!token._timeElapsedQuery) {
  17167. return -1;
  17168. }
  17169. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17170. this._deleteTimeQuery(token._timeElapsedQuery);
  17171. token._timeElapsedQuery = null;
  17172. token._timeElapsedQueryEnded = false;
  17173. this._currentNonTimestampToken = null;
  17174. }
  17175. return result;
  17176. }
  17177. return -1;
  17178. };
  17179. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17180. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17181. };
  17182. // Transform feedback
  17183. /**
  17184. * Creates a webGL transform feedback object
  17185. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17186. * @returns the webGL transform feedback object
  17187. */
  17188. Engine.prototype.createTransformFeedback = function () {
  17189. return this._gl.createTransformFeedback();
  17190. };
  17191. /**
  17192. * Delete a webGL transform feedback object
  17193. * @param value defines the webGL transform feedback object to delete
  17194. */
  17195. Engine.prototype.deleteTransformFeedback = function (value) {
  17196. this._gl.deleteTransformFeedback(value);
  17197. };
  17198. /**
  17199. * Bind a webGL transform feedback object to the webgl context
  17200. * @param value defines the webGL transform feedback object to bind
  17201. */
  17202. Engine.prototype.bindTransformFeedback = function (value) {
  17203. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17204. };
  17205. /**
  17206. * Begins a transform feedback operation
  17207. * @param usePoints defines if points or triangles must be used
  17208. */
  17209. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17210. if (usePoints === void 0) { usePoints = true; }
  17211. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17212. };
  17213. /**
  17214. * Ends a transform feedback operation
  17215. */
  17216. Engine.prototype.endTransformFeedback = function () {
  17217. this._gl.endTransformFeedback();
  17218. };
  17219. /**
  17220. * Specify the varyings to use with transform feedback
  17221. * @param program defines the associated webGL program
  17222. * @param value defines the list of strings representing the varying names
  17223. */
  17224. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17225. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17226. };
  17227. /**
  17228. * Bind a webGL buffer for a transform feedback operation
  17229. * @param value defines the webGL buffer to bind
  17230. */
  17231. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17232. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17233. };
  17234. /** @hidden */
  17235. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17236. var _this = this;
  17237. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17238. this._activeRequests.push(request);
  17239. request.onCompleteObservable.add(function (request) {
  17240. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17241. });
  17242. return request;
  17243. };
  17244. /** @hidden */
  17245. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17246. var _this = this;
  17247. return new Promise(function (resolve, reject) {
  17248. _this._loadFile(url, function (data) {
  17249. resolve(data);
  17250. }, undefined, database, useArrayBuffer, function (request, exception) {
  17251. reject(exception);
  17252. });
  17253. });
  17254. };
  17255. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17256. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17257. var onload = function (data) {
  17258. loadedFiles[index] = data;
  17259. loadedFiles._internalCount++;
  17260. if (loadedFiles._internalCount === 6) {
  17261. onfinish(loadedFiles);
  17262. }
  17263. };
  17264. var onerror = function (request, exception) {
  17265. if (onErrorCallBack && request) {
  17266. onErrorCallBack(request.status + " " + request.statusText, exception);
  17267. }
  17268. };
  17269. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17270. };
  17271. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17272. if (onError === void 0) { onError = null; }
  17273. var loadedFiles = [];
  17274. loadedFiles._internalCount = 0;
  17275. for (var index = 0; index < 6; index++) {
  17276. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17277. }
  17278. };
  17279. // Statics
  17280. /**
  17281. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17282. * @returns true if the engine can be created
  17283. * @ignorenaming
  17284. */
  17285. Engine.isSupported = function () {
  17286. try {
  17287. var tempcanvas = document.createElement("canvas");
  17288. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17289. return gl != null && !!window.WebGLRenderingContext;
  17290. }
  17291. catch (e) {
  17292. return false;
  17293. }
  17294. };
  17295. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17296. Engine.ExceptionList = [
  17297. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17298. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17299. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17300. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17301. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17302. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17303. ];
  17304. /** Gets the list of created engines */
  17305. Engine.Instances = new Array();
  17306. // Const statics
  17307. Engine._ALPHA_DISABLE = 0;
  17308. Engine._ALPHA_ADD = 1;
  17309. Engine._ALPHA_COMBINE = 2;
  17310. Engine._ALPHA_SUBTRACT = 3;
  17311. Engine._ALPHA_MULTIPLY = 4;
  17312. Engine._ALPHA_MAXIMIZED = 5;
  17313. Engine._ALPHA_ONEONE = 6;
  17314. Engine._ALPHA_PREMULTIPLIED = 7;
  17315. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17316. Engine._ALPHA_INTERPOLATE = 9;
  17317. Engine._ALPHA_SCREENMODE = 10;
  17318. Engine._DELAYLOADSTATE_NONE = 0;
  17319. Engine._DELAYLOADSTATE_LOADED = 1;
  17320. Engine._DELAYLOADSTATE_LOADING = 2;
  17321. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17322. Engine._TEXTUREFORMAT_ALPHA = 0;
  17323. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17324. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17325. Engine._TEXTUREFORMAT_RGB = 4;
  17326. Engine._TEXTUREFORMAT_RGBA = 5;
  17327. Engine._TEXTUREFORMAT_R32F = 6;
  17328. Engine._TEXTUREFORMAT_RG32F = 7;
  17329. Engine._TEXTUREFORMAT_RGB32F = 8;
  17330. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17331. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17332. Engine._TEXTURETYPE_FLOAT = 1;
  17333. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17334. // Depht or Stencil test Constants.
  17335. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17336. 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.
  17337. 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.
  17338. 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.
  17339. 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.
  17340. 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.
  17341. 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.
  17342. 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.
  17343. // Stencil Actions Constants.
  17344. Engine._KEEP = 0x1E00;
  17345. Engine._REPLACE = 0x1E01;
  17346. Engine._INCR = 0x1E02;
  17347. Engine._DECR = 0x1E03;
  17348. Engine._INVERT = 0x150A;
  17349. Engine._INCR_WRAP = 0x8507;
  17350. Engine._DECR_WRAP = 0x8508;
  17351. // Texture rescaling mode
  17352. Engine._SCALEMODE_FLOOR = 1;
  17353. Engine._SCALEMODE_NEAREST = 2;
  17354. Engine._SCALEMODE_CEILING = 3;
  17355. // Updatable statics so stick with vars here
  17356. /**
  17357. * Gets or sets the epsilon value used by collision engine
  17358. */
  17359. Engine.CollisionsEpsilon = 0.001;
  17360. /**
  17361. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17362. */
  17363. Engine.CodeRepository = "src/";
  17364. /**
  17365. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17366. */
  17367. Engine.ShadersRepository = "src/Shaders/";
  17368. return Engine;
  17369. }());
  17370. BABYLON.Engine = Engine;
  17371. })(BABYLON || (BABYLON = {}));
  17372. //# sourceMappingURL=babylon.engine.js.map
  17373. var BABYLON;
  17374. (function (BABYLON) {
  17375. /**
  17376. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17377. */
  17378. var Node = /** @class */ (function () {
  17379. /**
  17380. * Creates a new Node
  17381. * @param {string} name - the name and id to be given to this node
  17382. * @param {BABYLON.Scene} the scene this node will be added to
  17383. */
  17384. function Node(name, scene) {
  17385. if (scene === void 0) { scene = null; }
  17386. /**
  17387. * Gets or sets a string used to store user defined state for the node
  17388. */
  17389. this.state = "";
  17390. /**
  17391. * Gets or sets an object used to store user defined information for the node
  17392. */
  17393. this.metadata = null;
  17394. /**
  17395. * Gets or sets a boolean used to define if the node must be serialized
  17396. */
  17397. this.doNotSerialize = false;
  17398. /** @hidden */
  17399. this._isDisposed = false;
  17400. /**
  17401. * Gets a list of Animations associated with the node
  17402. */
  17403. this.animations = new Array();
  17404. this._ranges = {};
  17405. this._isEnabled = true;
  17406. this._isReady = true;
  17407. /** @hidden */
  17408. this._currentRenderId = -1;
  17409. this._parentRenderId = -1;
  17410. this._childRenderId = -1;
  17411. this._animationPropertiesOverride = null;
  17412. /**
  17413. * An event triggered when the mesh is disposed
  17414. */
  17415. this.onDisposeObservable = new BABYLON.Observable();
  17416. // Behaviors
  17417. this._behaviors = new Array();
  17418. this.name = name;
  17419. this.id = name;
  17420. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17421. this.uniqueId = this._scene.getUniqueId();
  17422. this._initCache();
  17423. }
  17424. /**
  17425. * Gets a boolean indicating if the node has been disposed
  17426. * @returns true if the node was disposed
  17427. */
  17428. Node.prototype.isDisposed = function () {
  17429. return this._isDisposed;
  17430. };
  17431. Object.defineProperty(Node.prototype, "parent", {
  17432. get: function () {
  17433. return this._parentNode;
  17434. },
  17435. /**
  17436. * Gets or sets the parent of the node
  17437. */
  17438. set: function (parent) {
  17439. if (this._parentNode === parent) {
  17440. return;
  17441. }
  17442. // Remove self from list of children of parent
  17443. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17444. var index = this._parentNode._children.indexOf(this);
  17445. if (index !== -1) {
  17446. this._parentNode._children.splice(index, 1);
  17447. }
  17448. }
  17449. // Store new parent
  17450. this._parentNode = parent;
  17451. // Add as child to new parent
  17452. if (this._parentNode) {
  17453. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17454. this._parentNode._children = new Array();
  17455. }
  17456. this._parentNode._children.push(this);
  17457. }
  17458. },
  17459. enumerable: true,
  17460. configurable: true
  17461. });
  17462. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17463. /**
  17464. * Gets or sets the animation properties override
  17465. */
  17466. get: function () {
  17467. if (!this._animationPropertiesOverride) {
  17468. return this._scene.animationPropertiesOverride;
  17469. }
  17470. return this._animationPropertiesOverride;
  17471. },
  17472. set: function (value) {
  17473. this._animationPropertiesOverride = value;
  17474. },
  17475. enumerable: true,
  17476. configurable: true
  17477. });
  17478. /**
  17479. * Gets a string idenfifying the name of the class
  17480. * @returns "Node" string
  17481. */
  17482. Node.prototype.getClassName = function () {
  17483. return "Node";
  17484. };
  17485. Object.defineProperty(Node.prototype, "onDispose", {
  17486. /**
  17487. * Sets a callback that will be raised when the node will be disposed
  17488. */
  17489. set: function (callback) {
  17490. if (this._onDisposeObserver) {
  17491. this.onDisposeObservable.remove(this._onDisposeObserver);
  17492. }
  17493. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17494. },
  17495. enumerable: true,
  17496. configurable: true
  17497. });
  17498. /**
  17499. * Gets the scene of the node
  17500. * @returns a {BABYLON.Scene}
  17501. */
  17502. Node.prototype.getScene = function () {
  17503. return this._scene;
  17504. };
  17505. /**
  17506. * Gets the engine of the node
  17507. * @returns a {BABYLON.Engine}
  17508. */
  17509. Node.prototype.getEngine = function () {
  17510. return this._scene.getEngine();
  17511. };
  17512. /**
  17513. * Attach a behavior to the node
  17514. * @see http://doc.babylonjs.com/features/behaviour
  17515. * @param behavior defines the behavior to attach
  17516. * @returns the current Node
  17517. */
  17518. Node.prototype.addBehavior = function (behavior) {
  17519. var _this = this;
  17520. var index = this._behaviors.indexOf(behavior);
  17521. if (index !== -1) {
  17522. return this;
  17523. }
  17524. behavior.init();
  17525. if (this._scene.isLoading) {
  17526. // We defer the attach when the scene will be loaded
  17527. var observer = this._scene.onDataLoadedObservable.add(function () {
  17528. behavior.attach(_this);
  17529. setTimeout(function () {
  17530. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17531. _this._scene.onDataLoadedObservable.remove(observer);
  17532. }, 0);
  17533. });
  17534. }
  17535. else {
  17536. behavior.attach(this);
  17537. }
  17538. this._behaviors.push(behavior);
  17539. return this;
  17540. };
  17541. /**
  17542. * Remove an attached behavior
  17543. * @see http://doc.babylonjs.com/features/behaviour
  17544. * @param behavior defines the behavior to attach
  17545. * @returns the current Node
  17546. */
  17547. Node.prototype.removeBehavior = function (behavior) {
  17548. var index = this._behaviors.indexOf(behavior);
  17549. if (index === -1) {
  17550. return this;
  17551. }
  17552. this._behaviors[index].detach();
  17553. this._behaviors.splice(index, 1);
  17554. return this;
  17555. };
  17556. Object.defineProperty(Node.prototype, "behaviors", {
  17557. /**
  17558. * Gets the list of attached behaviors
  17559. * @see http://doc.babylonjs.com/features/behaviour
  17560. */
  17561. get: function () {
  17562. return this._behaviors;
  17563. },
  17564. enumerable: true,
  17565. configurable: true
  17566. });
  17567. /**
  17568. * Gets an attached behavior by name
  17569. * @param name defines the name of the behavior to look for
  17570. * @see http://doc.babylonjs.com/features/behaviour
  17571. * @returns null if behavior was not found else the requested behavior
  17572. */
  17573. Node.prototype.getBehaviorByName = function (name) {
  17574. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17575. var behavior = _a[_i];
  17576. if (behavior.name === name) {
  17577. return behavior;
  17578. }
  17579. }
  17580. return null;
  17581. };
  17582. /**
  17583. * Returns the world matrix of the node
  17584. * @returns a matrix containing the node's world matrix
  17585. */
  17586. Node.prototype.getWorldMatrix = function () {
  17587. return BABYLON.Matrix.Identity();
  17588. };
  17589. /** @hidden */
  17590. Node.prototype._getWorldMatrixDeterminant = function () {
  17591. return 1;
  17592. };
  17593. // override it in derived class if you add new variables to the cache
  17594. // and call the parent class method
  17595. /** @hidden */
  17596. Node.prototype._initCache = function () {
  17597. this._cache = {};
  17598. this._cache.parent = undefined;
  17599. };
  17600. /** @hidden */
  17601. Node.prototype.updateCache = function (force) {
  17602. if (!force && this.isSynchronized())
  17603. return;
  17604. this._cache.parent = this.parent;
  17605. this._updateCache();
  17606. };
  17607. // override it in derived class if you add new variables to the cache
  17608. // and call the parent class method if !ignoreParentClass
  17609. /** @hidden */
  17610. Node.prototype._updateCache = function (ignoreParentClass) {
  17611. };
  17612. // override it in derived class if you add new variables to the cache
  17613. /** @hidden */
  17614. Node.prototype._isSynchronized = function () {
  17615. return true;
  17616. };
  17617. /** @hidden */
  17618. Node.prototype._markSyncedWithParent = function () {
  17619. if (this.parent) {
  17620. this._parentRenderId = this.parent._childRenderId;
  17621. }
  17622. };
  17623. /** @hidden */
  17624. Node.prototype.isSynchronizedWithParent = function () {
  17625. if (!this.parent) {
  17626. return true;
  17627. }
  17628. if (this._parentRenderId !== this.parent._childRenderId) {
  17629. return false;
  17630. }
  17631. return this.parent.isSynchronized();
  17632. };
  17633. /** @hidden */
  17634. Node.prototype.isSynchronized = function (updateCache) {
  17635. var check = this.hasNewParent();
  17636. check = check || !this.isSynchronizedWithParent();
  17637. check = check || !this._isSynchronized();
  17638. if (updateCache)
  17639. this.updateCache(true);
  17640. return !check;
  17641. };
  17642. /** @hidden */
  17643. Node.prototype.hasNewParent = function (update) {
  17644. if (this._cache.parent === this.parent)
  17645. return false;
  17646. if (update)
  17647. this._cache.parent = this.parent;
  17648. return true;
  17649. };
  17650. /**
  17651. * Is this node ready to be used/rendered
  17652. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17653. * @return true if the node is ready
  17654. */
  17655. Node.prototype.isReady = function (completeCheck) {
  17656. if (completeCheck === void 0) { completeCheck = false; }
  17657. return this._isReady;
  17658. };
  17659. /**
  17660. * Is this node enabled?
  17661. * 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
  17662. * @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
  17663. * @return whether this node (and its parent) is enabled
  17664. */
  17665. Node.prototype.isEnabled = function (checkAncestors) {
  17666. if (checkAncestors === void 0) { checkAncestors = true; }
  17667. if (checkAncestors === false) {
  17668. return this._isEnabled;
  17669. }
  17670. if (this._isEnabled === false) {
  17671. return false;
  17672. }
  17673. if (this.parent !== undefined && this.parent !== null) {
  17674. return this.parent.isEnabled(checkAncestors);
  17675. }
  17676. return true;
  17677. };
  17678. /**
  17679. * Set the enabled state of this node
  17680. * @param value defines the new enabled state
  17681. */
  17682. Node.prototype.setEnabled = function (value) {
  17683. this._isEnabled = value;
  17684. };
  17685. /**
  17686. * Is this node a descendant of the given node?
  17687. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17688. * @param ancestor defines the parent node to inspect
  17689. * @returns a boolean indicating if this node is a descendant of the given node
  17690. */
  17691. Node.prototype.isDescendantOf = function (ancestor) {
  17692. if (this.parent) {
  17693. if (this.parent === ancestor) {
  17694. return true;
  17695. }
  17696. return this.parent.isDescendantOf(ancestor);
  17697. }
  17698. return false;
  17699. };
  17700. /** @hidden */
  17701. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17702. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17703. if (!this._children) {
  17704. return;
  17705. }
  17706. for (var index = 0; index < this._children.length; index++) {
  17707. var item = this._children[index];
  17708. if (!predicate || predicate(item)) {
  17709. results.push(item);
  17710. }
  17711. if (!directDescendantsOnly) {
  17712. item._getDescendants(results, false, predicate);
  17713. }
  17714. }
  17715. };
  17716. /**
  17717. * Will return all nodes that have this node as ascendant
  17718. * @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
  17719. * @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
  17720. * @return all children nodes of all types
  17721. */
  17722. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17723. var results = new Array();
  17724. this._getDescendants(results, directDescendantsOnly, predicate);
  17725. return results;
  17726. };
  17727. /**
  17728. * Get all child-meshes of this node
  17729. * @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
  17730. * @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
  17731. * @returns an array of {BABYLON.AbstractMesh}
  17732. */
  17733. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17734. var results = [];
  17735. this._getDescendants(results, directDescendantsOnly, function (node) {
  17736. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17737. });
  17738. return results;
  17739. };
  17740. /**
  17741. * Get all child-transformNodes of this node
  17742. * @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
  17743. * @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
  17744. * @returns an array of {BABYLON.TransformNode}
  17745. */
  17746. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17747. var results = [];
  17748. this._getDescendants(results, directDescendantsOnly, function (node) {
  17749. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17750. });
  17751. return results;
  17752. };
  17753. /**
  17754. * Get all direct children of this node
  17755. * @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
  17756. * @returns an array of {BABYLON.Node}
  17757. */
  17758. Node.prototype.getChildren = function (predicate) {
  17759. return this.getDescendants(true, predicate);
  17760. };
  17761. /** @hidden */
  17762. Node.prototype._setReady = function (state) {
  17763. if (state === this._isReady) {
  17764. return;
  17765. }
  17766. if (!state) {
  17767. this._isReady = false;
  17768. return;
  17769. }
  17770. if (this.onReady) {
  17771. this.onReady(this);
  17772. }
  17773. this._isReady = true;
  17774. };
  17775. /**
  17776. * Get an animation by name
  17777. * @param name defines the name of the animation to look for
  17778. * @returns null if not found else the requested animation
  17779. */
  17780. Node.prototype.getAnimationByName = function (name) {
  17781. for (var i = 0; i < this.animations.length; i++) {
  17782. var animation = this.animations[i];
  17783. if (animation.name === name) {
  17784. return animation;
  17785. }
  17786. }
  17787. return null;
  17788. };
  17789. /**
  17790. * Creates an animation range for this node
  17791. * @param name defines the name of the range
  17792. * @param from defines the starting key
  17793. * @param to defines the end key
  17794. */
  17795. Node.prototype.createAnimationRange = function (name, from, to) {
  17796. // check name not already in use
  17797. if (!this._ranges[name]) {
  17798. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17799. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17800. if (this.animations[i]) {
  17801. this.animations[i].createRange(name, from, to);
  17802. }
  17803. }
  17804. }
  17805. };
  17806. /**
  17807. * Delete a specific animation range
  17808. * @param name defines the name of the range to delete
  17809. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17810. */
  17811. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17812. if (deleteFrames === void 0) { deleteFrames = true; }
  17813. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17814. if (this.animations[i]) {
  17815. this.animations[i].deleteRange(name, deleteFrames);
  17816. }
  17817. }
  17818. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17819. };
  17820. /**
  17821. * Get an animation range by name
  17822. * @param name defines the name of the animation range to look for
  17823. * @returns null if not found else the requested animation range
  17824. */
  17825. Node.prototype.getAnimationRange = function (name) {
  17826. return this._ranges[name];
  17827. };
  17828. /**
  17829. * Will start the animation sequence
  17830. * @param name defines the range frames for animation sequence
  17831. * @param loop defines if the animation should loop (false by default)
  17832. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17833. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17834. * @returns the object created for this animation. If range does not exist, it will return null
  17835. */
  17836. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17837. var range = this.getAnimationRange(name);
  17838. if (!range) {
  17839. return null;
  17840. }
  17841. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17842. };
  17843. /**
  17844. * Serialize animation ranges into a JSON compatible object
  17845. * @returns serialization object
  17846. */
  17847. Node.prototype.serializeAnimationRanges = function () {
  17848. var serializationRanges = [];
  17849. for (var name in this._ranges) {
  17850. var localRange = this._ranges[name];
  17851. if (!localRange) {
  17852. continue;
  17853. }
  17854. var range = {};
  17855. range.name = name;
  17856. range.from = localRange.from;
  17857. range.to = localRange.to;
  17858. serializationRanges.push(range);
  17859. }
  17860. return serializationRanges;
  17861. };
  17862. /**
  17863. * Computes the world matrix of the node
  17864. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17865. * @returns the world matrix
  17866. */
  17867. Node.prototype.computeWorldMatrix = function (force) {
  17868. return BABYLON.Matrix.Identity();
  17869. };
  17870. /**
  17871. * Releases resources associated with this node.
  17872. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17873. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17874. */
  17875. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17876. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17877. if (!doNotRecurse) {
  17878. var nodes = this.getDescendants(true);
  17879. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17880. var node = nodes_1[_i];
  17881. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17882. }
  17883. }
  17884. else {
  17885. var transformNodes = this.getChildTransformNodes(true);
  17886. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17887. var transformNode = transformNodes_1[_a];
  17888. transformNode.parent = null;
  17889. transformNode.computeWorldMatrix(true);
  17890. }
  17891. }
  17892. this.parent = null;
  17893. // Callback
  17894. this.onDisposeObservable.notifyObservers(this);
  17895. this.onDisposeObservable.clear();
  17896. // Behaviors
  17897. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17898. var behavior = _c[_b];
  17899. behavior.detach();
  17900. }
  17901. this._behaviors = [];
  17902. this._isDisposed = true;
  17903. };
  17904. /**
  17905. * Parse animation range data from a serialization object and store them into a given node
  17906. * @param node defines where to store the animation ranges
  17907. * @param parsedNode defines the serialization object to read data from
  17908. * @param scene defines the hosting scene
  17909. */
  17910. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17911. if (parsedNode.ranges) {
  17912. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17913. var data = parsedNode.ranges[index];
  17914. node.createAnimationRange(data.name, data.from, data.to);
  17915. }
  17916. }
  17917. };
  17918. __decorate([
  17919. BABYLON.serialize()
  17920. ], Node.prototype, "name", void 0);
  17921. __decorate([
  17922. BABYLON.serialize()
  17923. ], Node.prototype, "id", void 0);
  17924. __decorate([
  17925. BABYLON.serialize()
  17926. ], Node.prototype, "uniqueId", void 0);
  17927. __decorate([
  17928. BABYLON.serialize()
  17929. ], Node.prototype, "state", void 0);
  17930. __decorate([
  17931. BABYLON.serialize()
  17932. ], Node.prototype, "metadata", void 0);
  17933. return Node;
  17934. }());
  17935. BABYLON.Node = Node;
  17936. })(BABYLON || (BABYLON = {}));
  17937. //# sourceMappingURL=babylon.node.js.map
  17938. var BABYLON;
  17939. (function (BABYLON) {
  17940. var BoundingSphere = /** @class */ (function () {
  17941. /**
  17942. * Creates a new bounding sphere
  17943. * @param min defines the minimum vector (in local space)
  17944. * @param max defines the maximum vector (in local space)
  17945. */
  17946. function BoundingSphere(min, max) {
  17947. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17948. this.reConstruct(min, max);
  17949. }
  17950. /**
  17951. * Recreates the entire bounding sphere from scratch
  17952. * @param min defines the new minimum vector (in local space)
  17953. * @param max defines the new maximum vector (in local space)
  17954. */
  17955. BoundingSphere.prototype.reConstruct = function (min, max) {
  17956. this.minimum = min.clone();
  17957. this.maximum = max.clone();
  17958. var distance = BABYLON.Vector3.Distance(min, max);
  17959. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17960. this.radius = distance * 0.5;
  17961. this.centerWorld = BABYLON.Vector3.Zero();
  17962. this._update(BABYLON.Matrix.Identity());
  17963. };
  17964. // Methods
  17965. BoundingSphere.prototype._update = function (world) {
  17966. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17967. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17968. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17969. };
  17970. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17971. for (var i = 0; i < 6; i++) {
  17972. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17973. return false;
  17974. }
  17975. return true;
  17976. };
  17977. BoundingSphere.prototype.intersectsPoint = function (point) {
  17978. var x = this.centerWorld.x - point.x;
  17979. var y = this.centerWorld.y - point.y;
  17980. var z = this.centerWorld.z - point.z;
  17981. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17982. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17983. return false;
  17984. return true;
  17985. };
  17986. // Statics
  17987. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17988. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17989. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17990. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17991. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17992. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17993. return false;
  17994. return true;
  17995. };
  17996. return BoundingSphere;
  17997. }());
  17998. BABYLON.BoundingSphere = BoundingSphere;
  17999. })(BABYLON || (BABYLON = {}));
  18000. //# sourceMappingURL=babylon.boundingSphere.js.map
  18001. var BABYLON;
  18002. (function (BABYLON) {
  18003. var BoundingBox = /** @class */ (function () {
  18004. /**
  18005. * Creates a new bounding box
  18006. * @param min defines the minimum vector (in local space)
  18007. * @param max defines the maximum vector (in local space)
  18008. */
  18009. function BoundingBox(min, max) {
  18010. this.vectorsWorld = new Array();
  18011. this.reConstruct(min, max);
  18012. }
  18013. // Methods
  18014. /**
  18015. * Recreates the entire bounding box from scratch
  18016. * @param min defines the new minimum vector (in local space)
  18017. * @param max defines the new maximum vector (in local space)
  18018. */
  18019. BoundingBox.prototype.reConstruct = function (min, max) {
  18020. this.minimum = min.clone();
  18021. this.maximum = max.clone();
  18022. // Bounding vectors
  18023. this.vectors = new Array();
  18024. this.vectors.push(this.minimum.clone());
  18025. this.vectors.push(this.maximum.clone());
  18026. this.vectors.push(this.minimum.clone());
  18027. this.vectors[2].x = this.maximum.x;
  18028. this.vectors.push(this.minimum.clone());
  18029. this.vectors[3].y = this.maximum.y;
  18030. this.vectors.push(this.minimum.clone());
  18031. this.vectors[4].z = this.maximum.z;
  18032. this.vectors.push(this.maximum.clone());
  18033. this.vectors[5].z = this.minimum.z;
  18034. this.vectors.push(this.maximum.clone());
  18035. this.vectors[6].x = this.minimum.x;
  18036. this.vectors.push(this.maximum.clone());
  18037. this.vectors[7].y = this.minimum.y;
  18038. // OBB
  18039. this.center = this.maximum.add(this.minimum).scale(0.5);
  18040. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18041. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18042. // World
  18043. for (var index = 0; index < this.vectors.length; index++) {
  18044. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18045. }
  18046. this.minimumWorld = BABYLON.Vector3.Zero();
  18047. this.maximumWorld = BABYLON.Vector3.Zero();
  18048. this.centerWorld = BABYLON.Vector3.Zero();
  18049. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18050. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18051. };
  18052. BoundingBox.prototype.getWorldMatrix = function () {
  18053. return this._worldMatrix;
  18054. };
  18055. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18056. this._worldMatrix.copyFrom(matrix);
  18057. return this;
  18058. };
  18059. BoundingBox.prototype._update = function (world) {
  18060. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18061. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18062. for (var index = 0; index < this.vectors.length; index++) {
  18063. var v = this.vectorsWorld[index];
  18064. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18065. if (v.x < this.minimumWorld.x)
  18066. this.minimumWorld.x = v.x;
  18067. if (v.y < this.minimumWorld.y)
  18068. this.minimumWorld.y = v.y;
  18069. if (v.z < this.minimumWorld.z)
  18070. this.minimumWorld.z = v.z;
  18071. if (v.x > this.maximumWorld.x)
  18072. this.maximumWorld.x = v.x;
  18073. if (v.y > this.maximumWorld.y)
  18074. this.maximumWorld.y = v.y;
  18075. if (v.z > this.maximumWorld.z)
  18076. this.maximumWorld.z = v.z;
  18077. }
  18078. // Extend
  18079. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18080. this.extendSizeWorld.scaleInPlace(0.5);
  18081. // OBB
  18082. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18083. this.centerWorld.scaleInPlace(0.5);
  18084. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18085. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18086. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18087. this._worldMatrix = world;
  18088. };
  18089. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18090. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18091. };
  18092. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18093. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18094. };
  18095. BoundingBox.prototype.intersectsPoint = function (point) {
  18096. var delta = -BABYLON.Epsilon;
  18097. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18098. return false;
  18099. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18100. return false;
  18101. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18102. return false;
  18103. return true;
  18104. };
  18105. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18106. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18107. };
  18108. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18109. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18110. return false;
  18111. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18112. return false;
  18113. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18114. return false;
  18115. return true;
  18116. };
  18117. // Statics
  18118. BoundingBox.Intersects = function (box0, box1) {
  18119. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18120. return false;
  18121. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18122. return false;
  18123. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18124. return false;
  18125. return true;
  18126. };
  18127. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18128. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18129. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18130. return (num <= (sphereRadius * sphereRadius));
  18131. };
  18132. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18133. for (var p = 0; p < 6; p++) {
  18134. for (var i = 0; i < 8; i++) {
  18135. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18136. return false;
  18137. }
  18138. }
  18139. }
  18140. return true;
  18141. };
  18142. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18143. for (var p = 0; p < 6; p++) {
  18144. var inCount = 8;
  18145. for (var i = 0; i < 8; i++) {
  18146. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18147. --inCount;
  18148. }
  18149. else {
  18150. break;
  18151. }
  18152. }
  18153. if (inCount === 0)
  18154. return false;
  18155. }
  18156. return true;
  18157. };
  18158. return BoundingBox;
  18159. }());
  18160. BABYLON.BoundingBox = BoundingBox;
  18161. })(BABYLON || (BABYLON = {}));
  18162. //# sourceMappingURL=babylon.boundingBox.js.map
  18163. var BABYLON;
  18164. (function (BABYLON) {
  18165. var computeBoxExtents = function (axis, box) {
  18166. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18167. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18168. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18169. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18170. var r = r0 + r1 + r2;
  18171. return {
  18172. min: p - r,
  18173. max: p + r
  18174. };
  18175. };
  18176. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18177. var axisOverlap = function (axis, box0, box1) {
  18178. var result0 = computeBoxExtents(axis, box0);
  18179. var result1 = computeBoxExtents(axis, box1);
  18180. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18181. };
  18182. var BoundingInfo = /** @class */ (function () {
  18183. function BoundingInfo(minimum, maximum) {
  18184. this.minimum = minimum;
  18185. this.maximum = maximum;
  18186. this._isLocked = false;
  18187. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18188. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18189. }
  18190. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18191. get: function () {
  18192. return this._isLocked;
  18193. },
  18194. set: function (value) {
  18195. this._isLocked = value;
  18196. },
  18197. enumerable: true,
  18198. configurable: true
  18199. });
  18200. // Methods
  18201. BoundingInfo.prototype.update = function (world) {
  18202. if (this._isLocked) {
  18203. return;
  18204. }
  18205. this.boundingBox._update(world);
  18206. this.boundingSphere._update(world);
  18207. };
  18208. /**
  18209. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18210. * @param center New center of the bounding info
  18211. * @param extend New extend of the bounding info
  18212. */
  18213. BoundingInfo.prototype.centerOn = function (center, extend) {
  18214. this.minimum = center.subtract(extend);
  18215. this.maximum = center.add(extend);
  18216. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18217. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18218. return this;
  18219. };
  18220. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18221. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18222. return false;
  18223. return this.boundingBox.isInFrustum(frustumPlanes);
  18224. };
  18225. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18226. /**
  18227. * Gets the world distance between the min and max points of the bounding box
  18228. */
  18229. get: function () {
  18230. var boundingBox = this.boundingBox;
  18231. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18232. return size.length();
  18233. },
  18234. enumerable: true,
  18235. configurable: true
  18236. });
  18237. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18238. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18239. };
  18240. BoundingInfo.prototype._checkCollision = function (collider) {
  18241. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18242. };
  18243. BoundingInfo.prototype.intersectsPoint = function (point) {
  18244. if (!this.boundingSphere.centerWorld) {
  18245. return false;
  18246. }
  18247. if (!this.boundingSphere.intersectsPoint(point)) {
  18248. return false;
  18249. }
  18250. if (!this.boundingBox.intersectsPoint(point)) {
  18251. return false;
  18252. }
  18253. return true;
  18254. };
  18255. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18256. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18257. return false;
  18258. }
  18259. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18260. return false;
  18261. }
  18262. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18263. return false;
  18264. }
  18265. if (!precise) {
  18266. return true;
  18267. }
  18268. var box0 = this.boundingBox;
  18269. var box1 = boundingInfo.boundingBox;
  18270. if (!axisOverlap(box0.directions[0], box0, box1))
  18271. return false;
  18272. if (!axisOverlap(box0.directions[1], box0, box1))
  18273. return false;
  18274. if (!axisOverlap(box0.directions[2], box0, box1))
  18275. return false;
  18276. if (!axisOverlap(box1.directions[0], box0, box1))
  18277. return false;
  18278. if (!axisOverlap(box1.directions[1], box0, box1))
  18279. return false;
  18280. if (!axisOverlap(box1.directions[2], box0, box1))
  18281. return false;
  18282. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18283. return false;
  18284. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18285. return false;
  18286. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18287. return false;
  18288. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18289. return false;
  18290. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18291. return false;
  18292. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18293. return false;
  18294. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18295. return false;
  18296. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18297. return false;
  18298. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18299. return false;
  18300. return true;
  18301. };
  18302. return BoundingInfo;
  18303. }());
  18304. BABYLON.BoundingInfo = BoundingInfo;
  18305. })(BABYLON || (BABYLON = {}));
  18306. //# sourceMappingURL=babylon.boundingInfo.js.map
  18307. var BABYLON;
  18308. (function (BABYLON) {
  18309. var TransformNode = /** @class */ (function (_super) {
  18310. __extends(TransformNode, _super);
  18311. function TransformNode(name, scene, isPure) {
  18312. if (scene === void 0) { scene = null; }
  18313. if (isPure === void 0) { isPure = true; }
  18314. var _this = _super.call(this, name, scene) || this;
  18315. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18316. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18317. _this._up = new BABYLON.Vector3(0, 1, 0);
  18318. _this._right = new BABYLON.Vector3(1, 0, 0);
  18319. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18320. // Properties
  18321. _this._rotation = BABYLON.Vector3.Zero();
  18322. _this._scaling = BABYLON.Vector3.One();
  18323. _this._isDirty = false;
  18324. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18325. _this.scalingDeterminant = 1;
  18326. _this.infiniteDistance = false;
  18327. _this.position = BABYLON.Vector3.Zero();
  18328. _this._localWorld = BABYLON.Matrix.Zero();
  18329. _this._worldMatrix = BABYLON.Matrix.Zero();
  18330. _this._worldMatrixDeterminant = 0;
  18331. _this._absolutePosition = BABYLON.Vector3.Zero();
  18332. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18333. _this._postMultiplyPivotMatrix = false;
  18334. _this._isWorldMatrixFrozen = false;
  18335. /**
  18336. * An event triggered after the world matrix is updated
  18337. */
  18338. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18339. _this._nonUniformScaling = false;
  18340. if (isPure) {
  18341. _this.getScene().addTransformNode(_this);
  18342. }
  18343. return _this;
  18344. }
  18345. /**
  18346. * Gets a string idenfifying the name of the class
  18347. * @returns "TransformNode" string
  18348. */
  18349. TransformNode.prototype.getClassName = function () {
  18350. return "TransformNode";
  18351. };
  18352. Object.defineProperty(TransformNode.prototype, "rotation", {
  18353. /**
  18354. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18355. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18356. * Default : (0.0, 0.0, 0.0)
  18357. */
  18358. get: function () {
  18359. return this._rotation;
  18360. },
  18361. set: function (newRotation) {
  18362. this._rotation = newRotation;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. Object.defineProperty(TransformNode.prototype, "scaling", {
  18368. /**
  18369. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18370. * Default : (1.0, 1.0, 1.0)
  18371. */
  18372. get: function () {
  18373. return this._scaling;
  18374. },
  18375. /**
  18376. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18377. * Default : (1.0, 1.0, 1.0)
  18378. */
  18379. set: function (newScaling) {
  18380. this._scaling = newScaling;
  18381. },
  18382. enumerable: true,
  18383. configurable: true
  18384. });
  18385. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18386. /**
  18387. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18388. * It's null by default.
  18389. * 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)
  18390. */
  18391. get: function () {
  18392. return this._rotationQuaternion;
  18393. },
  18394. set: function (quaternion) {
  18395. this._rotationQuaternion = quaternion;
  18396. //reset the rotation vector.
  18397. if (quaternion && this.rotation.length()) {
  18398. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18399. }
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. Object.defineProperty(TransformNode.prototype, "forward", {
  18405. /**
  18406. * The forward direction of that transform in world space.
  18407. */
  18408. get: function () {
  18409. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18410. },
  18411. enumerable: true,
  18412. configurable: true
  18413. });
  18414. Object.defineProperty(TransformNode.prototype, "up", {
  18415. /**
  18416. * The up direction of that transform in world space.
  18417. */
  18418. get: function () {
  18419. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18420. },
  18421. enumerable: true,
  18422. configurable: true
  18423. });
  18424. Object.defineProperty(TransformNode.prototype, "right", {
  18425. /**
  18426. * The right direction of that transform in world space.
  18427. */
  18428. get: function () {
  18429. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18430. },
  18431. enumerable: true,
  18432. configurable: true
  18433. });
  18434. /**
  18435. * Returns the latest update of the World matrix
  18436. * Returns a Matrix.
  18437. */
  18438. TransformNode.prototype.getWorldMatrix = function () {
  18439. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18440. this.computeWorldMatrix();
  18441. }
  18442. return this._worldMatrix;
  18443. };
  18444. /** @hidden */
  18445. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18446. return this._worldMatrixDeterminant;
  18447. };
  18448. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18449. /**
  18450. * Returns directly the latest state of the mesh World matrix.
  18451. * A Matrix is returned.
  18452. */
  18453. get: function () {
  18454. return this._worldMatrix;
  18455. },
  18456. enumerable: true,
  18457. configurable: true
  18458. });
  18459. /**
  18460. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18461. * Returns the TransformNode.
  18462. */
  18463. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18464. this._poseMatrix.copyFrom(matrix);
  18465. return this;
  18466. };
  18467. /**
  18468. * Returns the mesh Pose matrix.
  18469. * Returned object : Matrix
  18470. */
  18471. TransformNode.prototype.getPoseMatrix = function () {
  18472. return this._poseMatrix;
  18473. };
  18474. TransformNode.prototype._isSynchronized = function () {
  18475. if (this._isDirty) {
  18476. return false;
  18477. }
  18478. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18479. return false;
  18480. if (this._cache.pivotMatrixUpdated) {
  18481. return false;
  18482. }
  18483. if (this.infiniteDistance) {
  18484. return false;
  18485. }
  18486. if (!this._cache.position.equals(this.position))
  18487. return false;
  18488. if (this.rotationQuaternion) {
  18489. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18490. return false;
  18491. }
  18492. if (!this._cache.rotation.equals(this.rotation))
  18493. return false;
  18494. if (!this._cache.scaling.equals(this.scaling))
  18495. return false;
  18496. return true;
  18497. };
  18498. TransformNode.prototype._initCache = function () {
  18499. _super.prototype._initCache.call(this);
  18500. this._cache.localMatrixUpdated = false;
  18501. this._cache.position = BABYLON.Vector3.Zero();
  18502. this._cache.scaling = BABYLON.Vector3.Zero();
  18503. this._cache.rotation = BABYLON.Vector3.Zero();
  18504. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18505. this._cache.billboardMode = -1;
  18506. };
  18507. TransformNode.prototype.markAsDirty = function (property) {
  18508. if (property === "rotation") {
  18509. this.rotationQuaternion = null;
  18510. }
  18511. this._currentRenderId = Number.MAX_VALUE;
  18512. this._isDirty = true;
  18513. return this;
  18514. };
  18515. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18516. /**
  18517. * Returns the current mesh absolute position.
  18518. * Retuns a Vector3.
  18519. */
  18520. get: function () {
  18521. return this._absolutePosition;
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. /**
  18527. * Sets a new matrix to apply before all other transformation
  18528. * @param matrix defines the transform matrix
  18529. * @returns the current TransformNode
  18530. */
  18531. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18532. return this.setPivotMatrix(matrix, false);
  18533. };
  18534. /**
  18535. * Sets a new pivot matrix to the current node
  18536. * @param matrix defines the new pivot matrix to use
  18537. * @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
  18538. * @returns the current TransformNode
  18539. */
  18540. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18541. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18542. this._pivotMatrix = matrix.clone();
  18543. this._cache.pivotMatrixUpdated = true;
  18544. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18545. if (this._postMultiplyPivotMatrix) {
  18546. if (!this._pivotMatrixInverse) {
  18547. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18548. }
  18549. else {
  18550. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18551. }
  18552. }
  18553. return this;
  18554. };
  18555. /**
  18556. * Returns the mesh pivot matrix.
  18557. * Default : Identity.
  18558. * A Matrix is returned.
  18559. */
  18560. TransformNode.prototype.getPivotMatrix = function () {
  18561. return this._pivotMatrix;
  18562. };
  18563. /**
  18564. * Prevents the World matrix to be computed any longer.
  18565. * Returns the TransformNode.
  18566. */
  18567. TransformNode.prototype.freezeWorldMatrix = function () {
  18568. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18569. this.computeWorldMatrix(true);
  18570. this._isWorldMatrixFrozen = true;
  18571. return this;
  18572. };
  18573. /**
  18574. * Allows back the World matrix computation.
  18575. * Returns the TransformNode.
  18576. */
  18577. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18578. this._isWorldMatrixFrozen = false;
  18579. this.computeWorldMatrix(true);
  18580. return this;
  18581. };
  18582. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18583. /**
  18584. * True if the World matrix has been frozen.
  18585. * Returns a boolean.
  18586. */
  18587. get: function () {
  18588. return this._isWorldMatrixFrozen;
  18589. },
  18590. enumerable: true,
  18591. configurable: true
  18592. });
  18593. /**
  18594. * Retuns the mesh absolute position in the World.
  18595. * Returns a Vector3.
  18596. */
  18597. TransformNode.prototype.getAbsolutePosition = function () {
  18598. this.computeWorldMatrix();
  18599. return this._absolutePosition;
  18600. };
  18601. /**
  18602. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18603. * Returns the TransformNode.
  18604. */
  18605. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18606. if (!absolutePosition) {
  18607. return this;
  18608. }
  18609. var absolutePositionX;
  18610. var absolutePositionY;
  18611. var absolutePositionZ;
  18612. if (absolutePosition.x === undefined) {
  18613. if (arguments.length < 3) {
  18614. return this;
  18615. }
  18616. absolutePositionX = arguments[0];
  18617. absolutePositionY = arguments[1];
  18618. absolutePositionZ = arguments[2];
  18619. }
  18620. else {
  18621. absolutePositionX = absolutePosition.x;
  18622. absolutePositionY = absolutePosition.y;
  18623. absolutePositionZ = absolutePosition.z;
  18624. }
  18625. if (this.parent) {
  18626. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18627. invertParentWorldMatrix.invert();
  18628. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18629. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18630. }
  18631. else {
  18632. this.position.x = absolutePositionX;
  18633. this.position.y = absolutePositionY;
  18634. this.position.z = absolutePositionZ;
  18635. }
  18636. return this;
  18637. };
  18638. /**
  18639. * Sets the mesh position in its local space.
  18640. * Returns the TransformNode.
  18641. */
  18642. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18643. this.computeWorldMatrix();
  18644. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18645. return this;
  18646. };
  18647. /**
  18648. * Returns the mesh position in the local space from the current World matrix values.
  18649. * Returns a new Vector3.
  18650. */
  18651. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18652. this.computeWorldMatrix();
  18653. var invLocalWorldMatrix = this._localWorld.clone();
  18654. invLocalWorldMatrix.invert();
  18655. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18656. };
  18657. /**
  18658. * Translates the mesh along the passed Vector3 in its local space.
  18659. * Returns the TransformNode.
  18660. */
  18661. TransformNode.prototype.locallyTranslate = function (vector3) {
  18662. this.computeWorldMatrix(true);
  18663. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18664. return this;
  18665. };
  18666. /**
  18667. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18668. * @param targetPoint the position (must be in same space as current mesh) to look at
  18669. * @param yawCor optional yaw (y-axis) correction in radians
  18670. * @param pitchCor optional pitch (x-axis) correction in radians
  18671. * @param rollCor optional roll (z-axis) correction in radians
  18672. * @param space the choosen space of the target
  18673. * @returns the TransformNode.
  18674. */
  18675. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18676. if (yawCor === void 0) { yawCor = 0; }
  18677. if (pitchCor === void 0) { pitchCor = 0; }
  18678. if (rollCor === void 0) { rollCor = 0; }
  18679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18680. var dv = TransformNode._lookAtVectorCache;
  18681. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18682. targetPoint.subtractToRef(pos, dv);
  18683. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18684. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18685. var pitch = Math.atan2(dv.y, len);
  18686. if (this.rotationQuaternion) {
  18687. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18688. }
  18689. else {
  18690. this.rotation.x = pitch + pitchCor;
  18691. this.rotation.y = yaw + yawCor;
  18692. this.rotation.z = rollCor;
  18693. }
  18694. return this;
  18695. };
  18696. /**
  18697. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18698. * This Vector3 is expressed in the World space.
  18699. */
  18700. TransformNode.prototype.getDirection = function (localAxis) {
  18701. var result = BABYLON.Vector3.Zero();
  18702. this.getDirectionToRef(localAxis, result);
  18703. return result;
  18704. };
  18705. /**
  18706. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18707. * localAxis is expressed in the mesh local space.
  18708. * result is computed in the Wordl space from the mesh World matrix.
  18709. * Returns the TransformNode.
  18710. */
  18711. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18712. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18713. return this;
  18714. };
  18715. /**
  18716. * Sets a new pivot point to the current node
  18717. * @param point defines the new pivot point to use
  18718. * @param space defines if the point is in world or local space (local by default)
  18719. * @returns the current TransformNode
  18720. */
  18721. TransformNode.prototype.setPivotPoint = function (point, space) {
  18722. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18723. if (this.getScene().getRenderId() == 0) {
  18724. this.computeWorldMatrix(true);
  18725. }
  18726. var wm = this.getWorldMatrix();
  18727. if (space == BABYLON.Space.WORLD) {
  18728. var tmat = BABYLON.Tmp.Matrix[0];
  18729. wm.invertToRef(tmat);
  18730. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18731. }
  18732. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18733. };
  18734. /**
  18735. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18736. */
  18737. TransformNode.prototype.getPivotPoint = function () {
  18738. var point = BABYLON.Vector3.Zero();
  18739. this.getPivotPointToRef(point);
  18740. return point;
  18741. };
  18742. /**
  18743. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18744. * Returns the TransformNode.
  18745. */
  18746. TransformNode.prototype.getPivotPointToRef = function (result) {
  18747. result.x = -this._pivotMatrix.m[12];
  18748. result.y = -this._pivotMatrix.m[13];
  18749. result.z = -this._pivotMatrix.m[14];
  18750. return this;
  18751. };
  18752. /**
  18753. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18754. */
  18755. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18756. var point = BABYLON.Vector3.Zero();
  18757. this.getAbsolutePivotPointToRef(point);
  18758. return point;
  18759. };
  18760. /**
  18761. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18762. * Returns the TransformNode.
  18763. */
  18764. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18765. result.x = this._pivotMatrix.m[12];
  18766. result.y = this._pivotMatrix.m[13];
  18767. result.z = this._pivotMatrix.m[14];
  18768. this.getPivotPointToRef(result);
  18769. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18770. return this;
  18771. };
  18772. /**
  18773. * Defines the passed node as the parent of the current node.
  18774. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18775. * Returns the TransformNode.
  18776. */
  18777. TransformNode.prototype.setParent = function (node) {
  18778. if (node === null) {
  18779. var rotation = BABYLON.Tmp.Quaternion[0];
  18780. var position = BABYLON.Tmp.Vector3[0];
  18781. var scale = BABYLON.Tmp.Vector3[1];
  18782. if (this.parent && this.parent.computeWorldMatrix) {
  18783. this.parent.computeWorldMatrix(true);
  18784. }
  18785. this.computeWorldMatrix(true);
  18786. this.getWorldMatrix().decompose(scale, rotation, position);
  18787. if (this.rotationQuaternion) {
  18788. this.rotationQuaternion.copyFrom(rotation);
  18789. }
  18790. else {
  18791. rotation.toEulerAnglesToRef(this.rotation);
  18792. }
  18793. this.scaling.x = scale.x;
  18794. this.scaling.y = scale.y;
  18795. this.scaling.z = scale.z;
  18796. this.position.x = position.x;
  18797. this.position.y = position.y;
  18798. this.position.z = position.z;
  18799. }
  18800. else {
  18801. var rotation = BABYLON.Tmp.Quaternion[0];
  18802. var position = BABYLON.Tmp.Vector3[0];
  18803. var scale = BABYLON.Tmp.Vector3[1];
  18804. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18805. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18806. this.computeWorldMatrix(true);
  18807. node.computeWorldMatrix(true);
  18808. node.getWorldMatrix().invertToRef(invParentMatrix);
  18809. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18810. diffMatrix.decompose(scale, rotation, position);
  18811. if (this.rotationQuaternion) {
  18812. this.rotationQuaternion.copyFrom(rotation);
  18813. }
  18814. else {
  18815. rotation.toEulerAnglesToRef(this.rotation);
  18816. }
  18817. this.position.x = position.x;
  18818. this.position.y = position.y;
  18819. this.position.z = position.z;
  18820. this.scaling.x = scale.x;
  18821. this.scaling.y = scale.y;
  18822. this.scaling.z = scale.z;
  18823. }
  18824. this.parent = node;
  18825. return this;
  18826. };
  18827. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18828. get: function () {
  18829. return this._nonUniformScaling;
  18830. },
  18831. enumerable: true,
  18832. configurable: true
  18833. });
  18834. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18835. if (this._nonUniformScaling === value) {
  18836. return false;
  18837. }
  18838. this._nonUniformScaling = true;
  18839. return true;
  18840. };
  18841. /**
  18842. * Attach the current TransformNode to another TransformNode associated with a bone
  18843. * @param bone Bone affecting the TransformNode
  18844. * @param affectedTransformNode TransformNode associated with the bone
  18845. */
  18846. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18847. this._transformToBoneReferal = affectedTransformNode;
  18848. this.parent = bone;
  18849. if (bone.getWorldMatrix().determinant() < 0) {
  18850. this.scalingDeterminant *= -1;
  18851. }
  18852. return this;
  18853. };
  18854. TransformNode.prototype.detachFromBone = function () {
  18855. if (!this.parent) {
  18856. return this;
  18857. }
  18858. if (this.parent.getWorldMatrix().determinant() < 0) {
  18859. this.scalingDeterminant *= -1;
  18860. }
  18861. this._transformToBoneReferal = null;
  18862. this.parent = null;
  18863. return this;
  18864. };
  18865. /**
  18866. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18867. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18868. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18869. * The passed axis is also normalized.
  18870. * Returns the TransformNode.
  18871. */
  18872. TransformNode.prototype.rotate = function (axis, amount, space) {
  18873. axis.normalize();
  18874. if (!this.rotationQuaternion) {
  18875. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18876. this.rotation = BABYLON.Vector3.Zero();
  18877. }
  18878. var rotationQuaternion;
  18879. if (!space || space === BABYLON.Space.LOCAL) {
  18880. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18881. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18882. }
  18883. else {
  18884. if (this.parent) {
  18885. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18886. invertParentWorldMatrix.invert();
  18887. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18888. }
  18889. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18890. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18891. }
  18892. return this;
  18893. };
  18894. /**
  18895. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18896. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18897. * The passed axis is also normalized.
  18898. * Returns the TransformNode.
  18899. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18900. */
  18901. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18902. axis.normalize();
  18903. if (!this.rotationQuaternion) {
  18904. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18905. this.rotation.copyFromFloats(0, 0, 0);
  18906. }
  18907. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18908. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18909. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18910. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18911. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18912. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18913. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18914. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18915. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18916. return this;
  18917. };
  18918. /**
  18919. * Translates the mesh along the axis vector for the passed distance in the given space.
  18920. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18921. * Returns the TransformNode.
  18922. */
  18923. TransformNode.prototype.translate = function (axis, distance, space) {
  18924. var displacementVector = axis.scale(distance);
  18925. if (!space || space === BABYLON.Space.LOCAL) {
  18926. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18927. this.setPositionWithLocalVector(tempV3);
  18928. }
  18929. else {
  18930. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18931. }
  18932. return this;
  18933. };
  18934. /**
  18935. * Adds a rotation step to the mesh current rotation.
  18936. * x, y, z are Euler angles expressed in radians.
  18937. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18938. * This means this rotation is made in the mesh local space only.
  18939. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18940. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18941. * ```javascript
  18942. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18943. * ```
  18944. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18945. * 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.
  18946. * Returns the TransformNode.
  18947. */
  18948. TransformNode.prototype.addRotation = function (x, y, z) {
  18949. var rotationQuaternion;
  18950. if (this.rotationQuaternion) {
  18951. rotationQuaternion = this.rotationQuaternion;
  18952. }
  18953. else {
  18954. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18955. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18956. }
  18957. var accumulation = BABYLON.Tmp.Quaternion[0];
  18958. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18959. rotationQuaternion.multiplyInPlace(accumulation);
  18960. if (!this.rotationQuaternion) {
  18961. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18962. }
  18963. return this;
  18964. };
  18965. /**
  18966. * Computes the mesh World matrix and returns it.
  18967. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18968. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18969. * If the parameter `force`is set to `true`, the actual computation is done.
  18970. * Returns the mesh World Matrix.
  18971. */
  18972. TransformNode.prototype.computeWorldMatrix = function (force) {
  18973. if (this._isWorldMatrixFrozen) {
  18974. return this._worldMatrix;
  18975. }
  18976. if (!force && this.isSynchronized(true)) {
  18977. this._currentRenderId = this.getScene().getRenderId();
  18978. return this._worldMatrix;
  18979. }
  18980. this._cache.position.copyFrom(this.position);
  18981. this._cache.scaling.copyFrom(this.scaling);
  18982. this._cache.pivotMatrixUpdated = false;
  18983. this._cache.billboardMode = this.billboardMode;
  18984. this._currentRenderId = this.getScene().getRenderId();
  18985. this._childRenderId = this.getScene().getRenderId();
  18986. this._isDirty = false;
  18987. // Scaling
  18988. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18989. // Rotation
  18990. //rotate, if quaternion is set and rotation was used
  18991. if (this.rotationQuaternion) {
  18992. var len = this.rotation.length();
  18993. if (len) {
  18994. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18995. this.rotation.copyFromFloats(0, 0, 0);
  18996. }
  18997. }
  18998. if (this.rotationQuaternion) {
  18999. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19000. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19001. }
  19002. else {
  19003. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19004. this._cache.rotation.copyFrom(this.rotation);
  19005. }
  19006. // Translation
  19007. var camera = this.getScene().activeCamera;
  19008. if (this.infiniteDistance && !this.parent && camera) {
  19009. var cameraWorldMatrix = camera.getWorldMatrix();
  19010. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19011. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19012. }
  19013. else {
  19014. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19015. }
  19016. // Composing transformations
  19017. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19018. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19019. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19020. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19021. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19022. // Need to decompose each rotation here
  19023. var currentPosition = BABYLON.Tmp.Vector3[3];
  19024. if (this.parent && this.parent.getWorldMatrix) {
  19025. if (this._transformToBoneReferal) {
  19026. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19027. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19028. }
  19029. else {
  19030. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19031. }
  19032. }
  19033. else {
  19034. currentPosition.copyFrom(this.position);
  19035. }
  19036. currentPosition.subtractInPlace(camera.globalPosition);
  19037. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19038. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19039. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19040. }
  19041. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19042. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19043. }
  19044. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19045. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19046. }
  19047. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19048. }
  19049. else {
  19050. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19051. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19052. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19053. }
  19054. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19055. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19056. }
  19057. // Local world
  19058. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19059. // Parent
  19060. if (this.parent && this.parent.getWorldMatrix) {
  19061. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19062. if (this._transformToBoneReferal) {
  19063. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19064. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19065. }
  19066. else {
  19067. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19068. }
  19069. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19070. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19071. this._worldMatrix.copyFrom(this._localWorld);
  19072. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19073. }
  19074. else {
  19075. if (this._transformToBoneReferal) {
  19076. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19077. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19078. }
  19079. else {
  19080. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19081. }
  19082. }
  19083. this._markSyncedWithParent();
  19084. }
  19085. else {
  19086. this._worldMatrix.copyFrom(this._localWorld);
  19087. }
  19088. // Post multiply inverse of pivotMatrix
  19089. if (this._postMultiplyPivotMatrix) {
  19090. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19091. }
  19092. // Normal matrix
  19093. if (this.scaling.isNonUniform) {
  19094. this._updateNonUniformScalingState(true);
  19095. }
  19096. else if (this.parent && this.parent._nonUniformScaling) {
  19097. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19098. }
  19099. else {
  19100. this._updateNonUniformScalingState(false);
  19101. }
  19102. this._afterComputeWorldMatrix();
  19103. // Absolute position
  19104. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19105. // Callbacks
  19106. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19107. if (!this._poseMatrix) {
  19108. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19109. }
  19110. // Cache the determinant
  19111. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19112. return this._worldMatrix;
  19113. };
  19114. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19115. };
  19116. /**
  19117. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19118. * @param func: callback function to add
  19119. *
  19120. * Returns the TransformNode.
  19121. */
  19122. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19123. this.onAfterWorldMatrixUpdateObservable.add(func);
  19124. return this;
  19125. };
  19126. /**
  19127. * Removes a registered callback function.
  19128. * Returns the TransformNode.
  19129. */
  19130. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19131. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19132. return this;
  19133. };
  19134. /**
  19135. * Clone the current transform node
  19136. * Returns the new transform node
  19137. * @param name Name of the new clone
  19138. * @param newParent New parent for the clone
  19139. * @param doNotCloneChildren Do not clone children hierarchy
  19140. */
  19141. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19142. var _this = this;
  19143. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19144. result.name = name;
  19145. result.id = name;
  19146. if (newParent) {
  19147. result.parent = newParent;
  19148. }
  19149. if (!doNotCloneChildren) {
  19150. // Children
  19151. var directDescendants = this.getDescendants(true);
  19152. for (var index = 0; index < directDescendants.length; index++) {
  19153. var child = directDescendants[index];
  19154. if (child.clone) {
  19155. child.clone(name + "." + child.name, result);
  19156. }
  19157. }
  19158. }
  19159. return result;
  19160. };
  19161. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19162. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19163. serializationObject.type = this.getClassName();
  19164. // Parent
  19165. if (this.parent) {
  19166. serializationObject.parentId = this.parent.id;
  19167. }
  19168. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19169. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19170. }
  19171. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19172. serializationObject.isEnabled = this.isEnabled();
  19173. // Parent
  19174. if (this.parent) {
  19175. serializationObject.parentId = this.parent.id;
  19176. }
  19177. return serializationObject;
  19178. };
  19179. // Statics
  19180. /**
  19181. * Returns a new TransformNode object parsed from the source provided.
  19182. * The parameter `parsedMesh` is the source.
  19183. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19184. */
  19185. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19186. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19187. if (BABYLON.Tags) {
  19188. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19189. }
  19190. if (parsedTransformNode.localMatrix) {
  19191. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19192. }
  19193. else if (parsedTransformNode.pivotMatrix) {
  19194. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19195. }
  19196. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19197. // Parent
  19198. if (parsedTransformNode.parentId) {
  19199. transformNode._waitingParentId = parsedTransformNode.parentId;
  19200. }
  19201. return transformNode;
  19202. };
  19203. /**
  19204. * Releases resources associated with this transform node.
  19205. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19206. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19207. */
  19208. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19209. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19210. // Animations
  19211. this.getScene().stopAnimation(this);
  19212. // Remove from scene
  19213. this.getScene().removeTransformNode(this);
  19214. this.onAfterWorldMatrixUpdateObservable.clear();
  19215. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19216. };
  19217. // Statics
  19218. TransformNode.BILLBOARDMODE_NONE = 0;
  19219. TransformNode.BILLBOARDMODE_X = 1;
  19220. TransformNode.BILLBOARDMODE_Y = 2;
  19221. TransformNode.BILLBOARDMODE_Z = 4;
  19222. TransformNode.BILLBOARDMODE_ALL = 7;
  19223. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19224. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19225. __decorate([
  19226. BABYLON.serializeAsVector3()
  19227. ], TransformNode.prototype, "_rotation", void 0);
  19228. __decorate([
  19229. BABYLON.serializeAsQuaternion()
  19230. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19231. __decorate([
  19232. BABYLON.serializeAsVector3()
  19233. ], TransformNode.prototype, "_scaling", void 0);
  19234. __decorate([
  19235. BABYLON.serialize()
  19236. ], TransformNode.prototype, "billboardMode", void 0);
  19237. __decorate([
  19238. BABYLON.serialize()
  19239. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19240. __decorate([
  19241. BABYLON.serialize()
  19242. ], TransformNode.prototype, "infiniteDistance", void 0);
  19243. __decorate([
  19244. BABYLON.serializeAsVector3()
  19245. ], TransformNode.prototype, "position", void 0);
  19246. return TransformNode;
  19247. }(BABYLON.Node));
  19248. BABYLON.TransformNode = TransformNode;
  19249. })(BABYLON || (BABYLON = {}));
  19250. //# sourceMappingURL=babylon.transformNode.js.map
  19251. var BABYLON;
  19252. (function (BABYLON) {
  19253. /**
  19254. * Class used to store all common mesh properties
  19255. */
  19256. var AbstractMesh = /** @class */ (function (_super) {
  19257. __extends(AbstractMesh, _super);
  19258. // Constructor
  19259. /**
  19260. * Creates a new AbstractMesh
  19261. * @param name defines the name of the mesh
  19262. * @param scene defines the hosting scene
  19263. */
  19264. function AbstractMesh(name, scene) {
  19265. if (scene === void 0) { scene = null; }
  19266. var _this = _super.call(this, name, scene, false) || this;
  19267. _this._facetNb = 0; // facet number
  19268. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19269. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19270. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19271. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19272. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19273. _this._subDiv = {
  19274. max: 1,
  19275. X: 1,
  19276. Y: 1,
  19277. Z: 1
  19278. };
  19279. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19280. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19281. // Events
  19282. /**
  19283. * An event triggered when this mesh collides with another one
  19284. */
  19285. _this.onCollideObservable = new BABYLON.Observable();
  19286. /**
  19287. * An event triggered when the collision's position changes
  19288. */
  19289. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19290. /**
  19291. * An event triggered when material is changed
  19292. */
  19293. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19294. // Properties
  19295. /**
  19296. * Gets or sets the orientation for POV movement & rotation
  19297. */
  19298. _this.definedFacingForward = true;
  19299. /**
  19300. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19301. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19302. * * 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.
  19303. * @see http://doc.babylonjs.com/features/occlusionquery
  19304. */
  19305. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19306. /**
  19307. * 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:
  19308. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19309. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19310. * * 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.
  19311. * @see http://doc.babylonjs.com/features/occlusionquery
  19312. */
  19313. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19314. /**
  19315. * 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.
  19316. * The default value is -1 which means don't break the query and wait till the result
  19317. * @see http://doc.babylonjs.com/features/occlusionquery
  19318. */
  19319. _this.occlusionRetryCount = -1;
  19320. _this._occlusionInternalRetryCounter = 0;
  19321. _this._isOccluded = false;
  19322. _this._isOcclusionQueryInProgress = false;
  19323. _this._visibility = 1.0;
  19324. /** Gets or sets the alpha index used to sort transparent meshes
  19325. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19326. */
  19327. _this.alphaIndex = Number.MAX_VALUE;
  19328. /**
  19329. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19330. */
  19331. _this.isVisible = true;
  19332. /**
  19333. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19334. */
  19335. _this.isPickable = true;
  19336. /**
  19337. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19338. */
  19339. _this.showBoundingBox = false;
  19340. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19341. _this.showSubMeshesBoundingBox = false;
  19342. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19343. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19344. */
  19345. _this.isBlocker = false;
  19346. /**
  19347. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19348. */
  19349. _this.enablePointerMoveEvents = false;
  19350. /**
  19351. * Specifies the rendering group id for this mesh (0 by default)
  19352. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19353. */
  19354. _this.renderingGroupId = 0;
  19355. _this._receiveShadows = false;
  19356. /**
  19357. * Gets or sets a boolean indicating if the outline must be rendered as well
  19358. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19359. */
  19360. _this.renderOutline = false;
  19361. /** Defines color to use when rendering outline */
  19362. _this.outlineColor = BABYLON.Color3.Red();
  19363. /** Define width to use when rendering outline */
  19364. _this.outlineWidth = 0.02;
  19365. /**
  19366. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19367. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19368. */
  19369. _this.renderOverlay = false;
  19370. /** Defines color to use when rendering overlay */
  19371. _this.overlayColor = BABYLON.Color3.Red();
  19372. /** Defines alpha to use when rendering overlay */
  19373. _this.overlayAlpha = 0.5;
  19374. _this._hasVertexAlpha = false;
  19375. _this._useVertexColors = true;
  19376. _this._computeBonesUsingShaders = true;
  19377. _this._numBoneInfluencers = 4;
  19378. _this._applyFog = true;
  19379. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19380. _this.useOctreeForRenderingSelection = true;
  19381. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19382. _this.useOctreeForPicking = true;
  19383. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19384. _this.useOctreeForCollisions = true;
  19385. _this._layerMask = 0x0FFFFFFF;
  19386. /**
  19387. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19388. */
  19389. _this.alwaysSelectAsActiveMesh = false;
  19390. /**
  19391. * Gets or sets the current action manager
  19392. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19393. */
  19394. _this.actionManager = null;
  19395. /**
  19396. * Gets or sets impostor used for physic simulation
  19397. * @see http://doc.babylonjs.com/features/physics_engine
  19398. */
  19399. _this.physicsImpostor = null;
  19400. // Collisions
  19401. _this._checkCollisions = false;
  19402. _this._collisionMask = -1;
  19403. _this._collisionGroup = -1;
  19404. /**
  19405. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19406. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19407. */
  19408. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19409. /**
  19410. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19411. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19412. */
  19413. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19414. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19415. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19416. // Edges
  19417. /**
  19418. * Defines edge width used when edgesRenderer is enabled
  19419. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19420. */
  19421. _this.edgesWidth = 1;
  19422. /**
  19423. * Defines edge color used when edgesRenderer is enabled
  19424. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19425. */
  19426. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19427. // Cache
  19428. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19429. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19430. /** @hidden */
  19431. _this._renderId = 0;
  19432. /** @hidden */
  19433. _this._intersectionsInProgress = new Array();
  19434. /** @hidden */
  19435. _this._unIndexed = false;
  19436. /** @hidden */
  19437. _this._lightSources = new Array();
  19438. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19439. if (collidedMesh === void 0) { collidedMesh = null; }
  19440. //TODO move this to the collision coordinator!
  19441. if (_this.getScene().workerCollisions)
  19442. newPosition.multiplyInPlace(_this._collider._radius);
  19443. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19444. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19445. _this.position.addInPlace(_this._diffPositionForCollisions);
  19446. }
  19447. if (collidedMesh) {
  19448. _this.onCollideObservable.notifyObservers(collidedMesh);
  19449. }
  19450. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19451. };
  19452. _this.getScene().addMesh(_this);
  19453. _this._resyncLightSources();
  19454. return _this;
  19455. }
  19456. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19457. /**
  19458. * No billboard
  19459. */
  19460. get: function () {
  19461. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19467. /** Billboard on X axis */
  19468. get: function () {
  19469. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19470. },
  19471. enumerable: true,
  19472. configurable: true
  19473. });
  19474. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19475. /** Billboard on Y axis */
  19476. get: function () {
  19477. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19478. },
  19479. enumerable: true,
  19480. configurable: true
  19481. });
  19482. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19483. /** Billboard on Z axis */
  19484. get: function () {
  19485. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19486. },
  19487. enumerable: true,
  19488. configurable: true
  19489. });
  19490. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19491. /** Billboard on all axes */
  19492. get: function () {
  19493. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19494. },
  19495. enumerable: true,
  19496. configurable: true
  19497. });
  19498. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19499. /**
  19500. * Gets the number of facets in the mesh
  19501. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19502. */
  19503. get: function () {
  19504. return this._facetNb;
  19505. },
  19506. enumerable: true,
  19507. configurable: true
  19508. });
  19509. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19510. /**
  19511. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19512. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19513. */
  19514. get: function () {
  19515. return this._partitioningSubdivisions;
  19516. },
  19517. set: function (nb) {
  19518. this._partitioningSubdivisions = nb;
  19519. },
  19520. enumerable: true,
  19521. configurable: true
  19522. });
  19523. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19524. /**
  19525. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19526. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19527. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19528. */
  19529. get: function () {
  19530. return this._partitioningBBoxRatio;
  19531. },
  19532. set: function (ratio) {
  19533. this._partitioningBBoxRatio = ratio;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19539. /**
  19540. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19541. * Works only for updatable meshes.
  19542. * Doesn't work with multi-materials
  19543. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19544. */
  19545. get: function () {
  19546. return this._facetDepthSort;
  19547. },
  19548. set: function (sort) {
  19549. this._facetDepthSort = sort;
  19550. },
  19551. enumerable: true,
  19552. configurable: true
  19553. });
  19554. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19555. /**
  19556. * The location (Vector3) where the facet depth sort must be computed from.
  19557. * By default, the active camera position.
  19558. * Used only when facet depth sort is enabled
  19559. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19560. */
  19561. get: function () {
  19562. return this._facetDepthSortFrom;
  19563. },
  19564. set: function (location) {
  19565. this._facetDepthSortFrom = location;
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19571. /**
  19572. * gets a boolean indicating if facetData is enabled
  19573. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19574. */
  19575. get: function () {
  19576. return this._facetDataEnabled;
  19577. },
  19578. enumerable: true,
  19579. configurable: true
  19580. });
  19581. /** @hidden */
  19582. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19583. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19584. return false;
  19585. }
  19586. this._markSubMeshesAsMiscDirty();
  19587. return true;
  19588. };
  19589. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19590. /** Set a function to call when this mesh collides with another one */
  19591. set: function (callback) {
  19592. if (this._onCollideObserver) {
  19593. this.onCollideObservable.remove(this._onCollideObserver);
  19594. }
  19595. this._onCollideObserver = this.onCollideObservable.add(callback);
  19596. },
  19597. enumerable: true,
  19598. configurable: true
  19599. });
  19600. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19601. /** Set a function to call when the collision's position changes */
  19602. set: function (callback) {
  19603. if (this._onCollisionPositionChangeObserver) {
  19604. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19605. }
  19606. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19607. },
  19608. enumerable: true,
  19609. configurable: true
  19610. });
  19611. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19612. /**
  19613. * 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
  19614. * @see http://doc.babylonjs.com/features/occlusionquery
  19615. */
  19616. get: function () {
  19617. return this._isOccluded;
  19618. },
  19619. set: function (value) {
  19620. this._isOccluded = value;
  19621. },
  19622. enumerable: true,
  19623. configurable: true
  19624. });
  19625. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19626. /**
  19627. * Flag to check the progress status of the query
  19628. * @see http://doc.babylonjs.com/features/occlusionquery
  19629. */
  19630. get: function () {
  19631. return this._isOcclusionQueryInProgress;
  19632. },
  19633. enumerable: true,
  19634. configurable: true
  19635. });
  19636. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19637. /**
  19638. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19639. */
  19640. get: function () {
  19641. return this._visibility;
  19642. },
  19643. /**
  19644. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19645. */
  19646. set: function (value) {
  19647. if (this._visibility === value) {
  19648. return;
  19649. }
  19650. this._visibility = value;
  19651. this._markSubMeshesAsMiscDirty();
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(AbstractMesh.prototype, "material", {
  19657. /** Gets or sets current material */
  19658. get: function () {
  19659. return this._material;
  19660. },
  19661. set: function (value) {
  19662. if (this._material === value) {
  19663. return;
  19664. }
  19665. this._material = value;
  19666. if (this.onMaterialChangedObservable.hasObservers) {
  19667. this.onMaterialChangedObservable.notifyObservers(this);
  19668. }
  19669. if (!this.subMeshes) {
  19670. return;
  19671. }
  19672. this._unBindEffect();
  19673. },
  19674. enumerable: true,
  19675. configurable: true
  19676. });
  19677. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19678. /**
  19679. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19680. * @see http://doc.babylonjs.com/babylon101/shadows
  19681. */
  19682. get: function () {
  19683. return this._receiveShadows;
  19684. },
  19685. set: function (value) {
  19686. if (this._receiveShadows === value) {
  19687. return;
  19688. }
  19689. this._receiveShadows = value;
  19690. this._markSubMeshesAsLightDirty();
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19696. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19697. get: function () {
  19698. return this._hasVertexAlpha;
  19699. },
  19700. set: function (value) {
  19701. if (this._hasVertexAlpha === value) {
  19702. return;
  19703. }
  19704. this._hasVertexAlpha = value;
  19705. this._markSubMeshesAsAttributesDirty();
  19706. this._markSubMeshesAsMiscDirty();
  19707. },
  19708. enumerable: true,
  19709. configurable: true
  19710. });
  19711. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19712. /** 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) */
  19713. get: function () {
  19714. return this._useVertexColors;
  19715. },
  19716. set: function (value) {
  19717. if (this._useVertexColors === value) {
  19718. return;
  19719. }
  19720. this._useVertexColors = value;
  19721. this._markSubMeshesAsAttributesDirty();
  19722. },
  19723. enumerable: true,
  19724. configurable: true
  19725. });
  19726. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19727. /**
  19728. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19729. */
  19730. get: function () {
  19731. return this._computeBonesUsingShaders;
  19732. },
  19733. set: function (value) {
  19734. if (this._computeBonesUsingShaders === value) {
  19735. return;
  19736. }
  19737. this._computeBonesUsingShaders = value;
  19738. this._markSubMeshesAsAttributesDirty();
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19744. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19745. get: function () {
  19746. return this._numBoneInfluencers;
  19747. },
  19748. set: function (value) {
  19749. if (this._numBoneInfluencers === value) {
  19750. return;
  19751. }
  19752. this._numBoneInfluencers = value;
  19753. this._markSubMeshesAsAttributesDirty();
  19754. },
  19755. enumerable: true,
  19756. configurable: true
  19757. });
  19758. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19759. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19760. get: function () {
  19761. return this._applyFog;
  19762. },
  19763. set: function (value) {
  19764. if (this._applyFog === value) {
  19765. return;
  19766. }
  19767. this._applyFog = value;
  19768. this._markSubMeshesAsMiscDirty();
  19769. },
  19770. enumerable: true,
  19771. configurable: true
  19772. });
  19773. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19774. /**
  19775. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19776. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19777. */
  19778. get: function () {
  19779. return this._layerMask;
  19780. },
  19781. set: function (value) {
  19782. if (value === this._layerMask) {
  19783. return;
  19784. }
  19785. this._layerMask = value;
  19786. this._resyncLightSources();
  19787. },
  19788. enumerable: true,
  19789. configurable: true
  19790. });
  19791. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19792. /**
  19793. * Gets or sets a collision mask used to mask collisions (default is -1).
  19794. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19795. */
  19796. get: function () {
  19797. return this._collisionMask;
  19798. },
  19799. set: function (mask) {
  19800. this._collisionMask = !isNaN(mask) ? mask : -1;
  19801. },
  19802. enumerable: true,
  19803. configurable: true
  19804. });
  19805. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19806. /**
  19807. * Gets or sets the current collision group mask (-1 by default).
  19808. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19809. */
  19810. get: function () {
  19811. return this._collisionGroup;
  19812. },
  19813. set: function (mask) {
  19814. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19815. },
  19816. enumerable: true,
  19817. configurable: true
  19818. });
  19819. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19820. /** @hidden */
  19821. get: function () {
  19822. return null;
  19823. },
  19824. enumerable: true,
  19825. configurable: true
  19826. });
  19827. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19828. get: function () {
  19829. return this._skeleton;
  19830. },
  19831. /**
  19832. * Gets or sets a skeleton to apply skining transformations
  19833. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19834. */
  19835. set: function (value) {
  19836. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19837. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19838. }
  19839. if (value && value.needInitialSkinMatrix) {
  19840. value._registerMeshWithPoseMatrix(this);
  19841. }
  19842. this._skeleton = value;
  19843. if (!this._skeleton) {
  19844. this._bonesTransformMatrices = null;
  19845. }
  19846. this._markSubMeshesAsAttributesDirty();
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. /**
  19852. * Returns the string "AbstractMesh"
  19853. * @returns "AbstractMesh"
  19854. */
  19855. AbstractMesh.prototype.getClassName = function () {
  19856. return "AbstractMesh";
  19857. };
  19858. /**
  19859. * Gets a string representation of the current mesh
  19860. * @param fullDetails defines a boolean indicating if full details must be included
  19861. * @returns a string representation of the current mesh
  19862. */
  19863. AbstractMesh.prototype.toString = function (fullDetails) {
  19864. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19865. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19866. if (this._skeleton) {
  19867. ret += ", skeleton: " + this._skeleton.name;
  19868. }
  19869. if (fullDetails) {
  19870. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19871. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19872. }
  19873. return ret;
  19874. };
  19875. /** @hidden */
  19876. AbstractMesh.prototype._rebuild = function () {
  19877. if (this._occlusionQuery) {
  19878. this._occlusionQuery = null;
  19879. }
  19880. if (this._edgesRenderer) {
  19881. this._edgesRenderer._rebuild();
  19882. }
  19883. if (!this.subMeshes) {
  19884. return;
  19885. }
  19886. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19887. var subMesh = _a[_i];
  19888. subMesh._rebuild();
  19889. }
  19890. };
  19891. /** @hidden */
  19892. AbstractMesh.prototype._resyncLightSources = function () {
  19893. this._lightSources.length = 0;
  19894. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19895. var light = _a[_i];
  19896. if (!light.isEnabled()) {
  19897. continue;
  19898. }
  19899. if (light.canAffectMesh(this)) {
  19900. this._lightSources.push(light);
  19901. }
  19902. }
  19903. this._markSubMeshesAsLightDirty();
  19904. };
  19905. /** @hidden */
  19906. AbstractMesh.prototype._resyncLighSource = function (light) {
  19907. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19908. var index = this._lightSources.indexOf(light);
  19909. if (index === -1) {
  19910. if (!isIn) {
  19911. return;
  19912. }
  19913. this._lightSources.push(light);
  19914. }
  19915. else {
  19916. if (isIn) {
  19917. return;
  19918. }
  19919. this._lightSources.splice(index, 1);
  19920. }
  19921. this._markSubMeshesAsLightDirty();
  19922. };
  19923. /** @hidden */
  19924. AbstractMesh.prototype._unBindEffect = function () {
  19925. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19926. var subMesh = _a[_i];
  19927. subMesh.setEffect(null);
  19928. }
  19929. };
  19930. /** @hidden */
  19931. AbstractMesh.prototype._removeLightSource = function (light) {
  19932. var index = this._lightSources.indexOf(light);
  19933. if (index === -1) {
  19934. return;
  19935. }
  19936. this._lightSources.splice(index, 1);
  19937. this._markSubMeshesAsLightDirty();
  19938. };
  19939. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19940. if (!this.subMeshes) {
  19941. return;
  19942. }
  19943. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19944. var subMesh = _a[_i];
  19945. if (subMesh._materialDefines) {
  19946. func(subMesh._materialDefines);
  19947. }
  19948. }
  19949. };
  19950. /** @hidden */
  19951. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19952. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19953. };
  19954. /** @hidden */
  19955. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19956. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19957. };
  19958. /** @hidden */
  19959. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19960. if (!this.subMeshes) {
  19961. return;
  19962. }
  19963. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19964. var subMesh = _a[_i];
  19965. var material = subMesh.getMaterial();
  19966. if (material) {
  19967. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19968. }
  19969. }
  19970. };
  19971. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19972. /**
  19973. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19974. */
  19975. get: function () {
  19976. return this._scaling;
  19977. },
  19978. set: function (newScaling) {
  19979. this._scaling = newScaling;
  19980. if (this.physicsImpostor) {
  19981. this.physicsImpostor.forceUpdate();
  19982. }
  19983. },
  19984. enumerable: true,
  19985. configurable: true
  19986. });
  19987. // Methods
  19988. /**
  19989. * Disables the mesh edge rendering mode
  19990. * @returns the currentAbstractMesh
  19991. */
  19992. AbstractMesh.prototype.disableEdgesRendering = function () {
  19993. if (this._edgesRenderer) {
  19994. this._edgesRenderer.dispose();
  19995. this._edgesRenderer = null;
  19996. }
  19997. return this;
  19998. };
  19999. /**
  20000. * Enables the edge rendering mode on the mesh.
  20001. * This mode makes the mesh edges visible
  20002. * @param epsilon defines the maximal distance between two angles to detect a face
  20003. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20004. * @returns the currentAbstractMesh
  20005. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20006. */
  20007. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20008. if (epsilon === void 0) { epsilon = 0.95; }
  20009. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20010. this.disableEdgesRendering();
  20011. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20012. return this;
  20013. };
  20014. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20015. /**
  20016. * Returns true if the mesh is blocked. Implemented by child classes
  20017. */
  20018. get: function () {
  20019. return false;
  20020. },
  20021. enumerable: true,
  20022. configurable: true
  20023. });
  20024. /**
  20025. * Returns the mesh itself by default. Implemented by child classes
  20026. * @param camera defines the camera to use to pick the right LOD level
  20027. * @returns the currentAbstractMesh
  20028. */
  20029. AbstractMesh.prototype.getLOD = function (camera) {
  20030. return this;
  20031. };
  20032. /**
  20033. * Returns 0 by default. Implemented by child classes
  20034. * @returns an integer
  20035. */
  20036. AbstractMesh.prototype.getTotalVertices = function () {
  20037. return 0;
  20038. };
  20039. /**
  20040. * Returns null by default. Implemented by child classes
  20041. * @returns null
  20042. */
  20043. AbstractMesh.prototype.getIndices = function () {
  20044. return null;
  20045. };
  20046. /**
  20047. * Returns the array of the requested vertex data kind. Implemented by child classes
  20048. * @param kind defines the vertex data kind to use
  20049. * @returns null
  20050. */
  20051. AbstractMesh.prototype.getVerticesData = function (kind) {
  20052. return null;
  20053. };
  20054. /**
  20055. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20056. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20057. * Note that a new underlying VertexBuffer object is created each call.
  20058. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20059. * @param kind defines vertex data kind:
  20060. * * BABYLON.VertexBuffer.PositionKind
  20061. * * BABYLON.VertexBuffer.UVKind
  20062. * * BABYLON.VertexBuffer.UV2Kind
  20063. * * BABYLON.VertexBuffer.UV3Kind
  20064. * * BABYLON.VertexBuffer.UV4Kind
  20065. * * BABYLON.VertexBuffer.UV5Kind
  20066. * * BABYLON.VertexBuffer.UV6Kind
  20067. * * BABYLON.VertexBuffer.ColorKind
  20068. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20069. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20070. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20071. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20072. * @param data defines the data source
  20073. * @param updatable defines if the data must be flagged as updatable (or static)
  20074. * @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
  20075. * @returns the current mesh
  20076. */
  20077. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20078. return this;
  20079. };
  20080. /**
  20081. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20082. * If the mesh has no geometry, it is simply returned as it is.
  20083. * @param kind defines vertex data kind:
  20084. * * BABYLON.VertexBuffer.PositionKind
  20085. * * BABYLON.VertexBuffer.UVKind
  20086. * * BABYLON.VertexBuffer.UV2Kind
  20087. * * BABYLON.VertexBuffer.UV3Kind
  20088. * * BABYLON.VertexBuffer.UV4Kind
  20089. * * BABYLON.VertexBuffer.UV5Kind
  20090. * * BABYLON.VertexBuffer.UV6Kind
  20091. * * BABYLON.VertexBuffer.ColorKind
  20092. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20093. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20094. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20095. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20096. * @param data defines the data source
  20097. * @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
  20098. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20099. * @returns the current mesh
  20100. */
  20101. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20102. return this;
  20103. };
  20104. /**
  20105. * Sets the mesh indices,
  20106. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20107. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20108. * @param totalVertices Defines the total number of vertices
  20109. * @returns the current mesh
  20110. */
  20111. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20112. return this;
  20113. };
  20114. /**
  20115. * Gets a boolean indicating if specific vertex data is present
  20116. * @param kind defines the vertex data kind to use
  20117. * @returns true is data kind is present
  20118. */
  20119. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20120. return false;
  20121. };
  20122. /**
  20123. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20124. * @returns a BoundingInfo
  20125. */
  20126. AbstractMesh.prototype.getBoundingInfo = function () {
  20127. if (this._masterMesh) {
  20128. return this._masterMesh.getBoundingInfo();
  20129. }
  20130. if (!this._boundingInfo) {
  20131. // this._boundingInfo is being created here
  20132. this._updateBoundingInfo();
  20133. }
  20134. // cannot be null.
  20135. return this._boundingInfo;
  20136. };
  20137. /**
  20138. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20139. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20140. * @returns the current mesh
  20141. */
  20142. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20143. if (includeDescendants === void 0) { includeDescendants = true; }
  20144. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20145. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20146. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20147. if (maxDimension === 0) {
  20148. return this;
  20149. }
  20150. var scale = 1 / maxDimension;
  20151. this.scaling.scaleInPlace(scale);
  20152. return this;
  20153. };
  20154. /**
  20155. * Overwrite the current bounding info
  20156. * @param boundingInfo defines the new bounding info
  20157. * @returns the current mesh
  20158. */
  20159. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20160. this._boundingInfo = boundingInfo;
  20161. return this;
  20162. };
  20163. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20164. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20165. get: function () {
  20166. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20167. },
  20168. enumerable: true,
  20169. configurable: true
  20170. });
  20171. /** @hidden */
  20172. AbstractMesh.prototype._preActivate = function () {
  20173. };
  20174. /** @hidden */
  20175. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20176. };
  20177. /** @hidden */
  20178. AbstractMesh.prototype._activate = function (renderId) {
  20179. this._renderId = renderId;
  20180. };
  20181. /**
  20182. * Gets the current world matrix
  20183. * @returns a Matrix
  20184. */
  20185. AbstractMesh.prototype.getWorldMatrix = function () {
  20186. if (this._masterMesh) {
  20187. return this._masterMesh.getWorldMatrix();
  20188. }
  20189. return _super.prototype.getWorldMatrix.call(this);
  20190. };
  20191. /** @hidden */
  20192. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20193. if (this._masterMesh) {
  20194. return this._masterMesh._getWorldMatrixDeterminant();
  20195. }
  20196. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20197. };
  20198. // ================================== Point of View Movement =================================
  20199. /**
  20200. * Perform relative position change from the point of view of behind the front of the mesh.
  20201. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20202. * Supports definition of mesh facing forward or backward
  20203. * @param amountRight defines the distance on the right axis
  20204. * @param amountUp defines the distance on the up axis
  20205. * @param amountForward defines the distance on the forward axis
  20206. * @returns the current mesh
  20207. */
  20208. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20209. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20210. return this;
  20211. };
  20212. /**
  20213. * Calculate relative position change from the point of view of behind the front of the mesh.
  20214. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20215. * Supports definition of mesh facing forward or backward
  20216. * @param amountRight defines the distance on the right axis
  20217. * @param amountUp defines the distance on the up axis
  20218. * @param amountForward defines the distance on the forward axis
  20219. * @returns the new displacement vector
  20220. */
  20221. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20222. var rotMatrix = new BABYLON.Matrix();
  20223. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20224. rotQuaternion.toRotationMatrix(rotMatrix);
  20225. var translationDelta = BABYLON.Vector3.Zero();
  20226. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20227. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20228. return translationDelta;
  20229. };
  20230. // ================================== Point of View Rotation =================================
  20231. /**
  20232. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20233. * Supports definition of mesh facing forward or backward
  20234. * @param flipBack defines the flip
  20235. * @param twirlClockwise defines the twirl
  20236. * @param tiltRight defines the tilt
  20237. * @returns the current mesh
  20238. */
  20239. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20240. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20241. return this;
  20242. };
  20243. /**
  20244. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20245. * Supports definition of mesh facing forward or backward.
  20246. * @param flipBack defines the flip
  20247. * @param twirlClockwise defines the twirl
  20248. * @param tiltRight defines the tilt
  20249. * @returns the new rotation vector
  20250. */
  20251. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20252. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20253. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20254. };
  20255. /**
  20256. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20257. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20258. * @returns the new bounding vectors
  20259. */
  20260. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20261. if (includeDescendants === void 0) { includeDescendants = true; }
  20262. // Ensures that all world matrix will be recomputed.
  20263. this.getScene().incrementRenderId();
  20264. this.computeWorldMatrix(true);
  20265. var min;
  20266. var max;
  20267. var boundingInfo = this.getBoundingInfo();
  20268. if (!this.subMeshes) {
  20269. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20270. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20271. }
  20272. else {
  20273. min = boundingInfo.boundingBox.minimumWorld;
  20274. max = boundingInfo.boundingBox.maximumWorld;
  20275. }
  20276. if (includeDescendants) {
  20277. var descendants = this.getDescendants(false);
  20278. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20279. var descendant = descendants_1[_i];
  20280. var childMesh = descendant;
  20281. childMesh.computeWorldMatrix(true);
  20282. //make sure we have the needed params to get mix and max
  20283. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20284. continue;
  20285. }
  20286. var childBoundingInfo = childMesh.getBoundingInfo();
  20287. var boundingBox = childBoundingInfo.boundingBox;
  20288. var minBox = boundingBox.minimumWorld;
  20289. var maxBox = boundingBox.maximumWorld;
  20290. BABYLON.Tools.CheckExtends(minBox, min, max);
  20291. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20292. }
  20293. }
  20294. return {
  20295. min: min,
  20296. max: max
  20297. };
  20298. };
  20299. /** @hidden */
  20300. AbstractMesh.prototype._updateBoundingInfo = function () {
  20301. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20302. this._boundingInfo.update(this.worldMatrixFromCache);
  20303. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20304. return this;
  20305. };
  20306. /** @hidden */
  20307. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20308. if (!this.subMeshes) {
  20309. return this;
  20310. }
  20311. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20312. var subMesh = this.subMeshes[subIndex];
  20313. if (!subMesh.IsGlobal) {
  20314. subMesh.updateBoundingInfo(matrix);
  20315. }
  20316. }
  20317. return this;
  20318. };
  20319. /** @hidden */
  20320. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20321. // Bounding info
  20322. this._updateBoundingInfo();
  20323. };
  20324. /**
  20325. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20326. * A mesh is in the frustum if its bounding box intersects the frustum
  20327. * @param frustumPlanes defines the frustum to test
  20328. * @returns true if the mesh is in the frustum planes
  20329. */
  20330. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20331. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20332. };
  20333. /**
  20334. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20335. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20336. * @param frustumPlanes defines the frustum to test
  20337. * @returns true if the mesh is completely in the frustum planes
  20338. */
  20339. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20340. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20341. };
  20342. /**
  20343. * True if the mesh intersects another mesh or a SolidParticle object
  20344. * @param mesh defines a target mesh or SolidParticle to test
  20345. * @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)
  20346. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20347. * @returns true if there is an intersection
  20348. */
  20349. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20350. if (precise === void 0) { precise = false; }
  20351. if (!this._boundingInfo || !mesh._boundingInfo) {
  20352. return false;
  20353. }
  20354. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20355. return true;
  20356. }
  20357. if (includeDescendants) {
  20358. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20359. var child = _a[_i];
  20360. if (child.intersectsMesh(mesh, precise, true)) {
  20361. return true;
  20362. }
  20363. }
  20364. }
  20365. return false;
  20366. };
  20367. /**
  20368. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20369. * @param point defines the point to test
  20370. * @returns true if there is an intersection
  20371. */
  20372. AbstractMesh.prototype.intersectsPoint = function (point) {
  20373. if (!this._boundingInfo) {
  20374. return false;
  20375. }
  20376. return this._boundingInfo.intersectsPoint(point);
  20377. };
  20378. /**
  20379. * Gets the current physics impostor
  20380. * @see http://doc.babylonjs.com/features/physics_engine
  20381. * @returns a physics impostor or null
  20382. */
  20383. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20384. return this.physicsImpostor;
  20385. };
  20386. /**
  20387. * Gets the position of the current mesh in camera space
  20388. * @param camera defines the camera to use
  20389. * @returns a position
  20390. */
  20391. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20392. if (camera === void 0) { camera = null; }
  20393. if (!camera) {
  20394. camera = this.getScene().activeCamera;
  20395. }
  20396. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20397. };
  20398. /**
  20399. * Returns the distance from the mesh to the active camera
  20400. * @param camera defines the camera to use
  20401. * @returns the distance
  20402. */
  20403. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20404. if (camera === void 0) { camera = null; }
  20405. if (!camera) {
  20406. camera = this.getScene().activeCamera;
  20407. }
  20408. return this.absolutePosition.subtract(camera.position).length();
  20409. };
  20410. /**
  20411. * Apply a physic impulse to the mesh
  20412. * @param force defines the force to apply
  20413. * @param contactPoint defines where to apply the force
  20414. * @returns the current mesh
  20415. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20416. */
  20417. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20418. if (!this.physicsImpostor) {
  20419. return this;
  20420. }
  20421. this.physicsImpostor.applyImpulse(force, contactPoint);
  20422. return this;
  20423. };
  20424. /**
  20425. * Creates a physic joint between two meshes
  20426. * @param otherMesh defines the other mesh to use
  20427. * @param pivot1 defines the pivot to use on this mesh
  20428. * @param pivot2 defines the pivot to use on the other mesh
  20429. * @param options defines additional options (can be plugin dependent)
  20430. * @returns the current mesh
  20431. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20432. */
  20433. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20434. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20435. return this;
  20436. }
  20437. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20438. mainPivot: pivot1,
  20439. connectedPivot: pivot2,
  20440. nativeParams: options
  20441. });
  20442. return this;
  20443. };
  20444. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20445. // Collisions
  20446. /**
  20447. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20448. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20449. */
  20450. get: function () {
  20451. return this._checkCollisions;
  20452. },
  20453. set: function (collisionEnabled) {
  20454. this._checkCollisions = collisionEnabled;
  20455. if (this.getScene().workerCollisions) {
  20456. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20457. }
  20458. },
  20459. enumerable: true,
  20460. configurable: true
  20461. });
  20462. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20463. /**
  20464. * Gets Collider object used to compute collisions (not physics)
  20465. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20466. */
  20467. get: function () {
  20468. return this._collider;
  20469. },
  20470. enumerable: true,
  20471. configurable: true
  20472. });
  20473. /**
  20474. * Move the mesh using collision engine
  20475. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20476. * @param displacement defines the requested displacement vector
  20477. * @returns the current mesh
  20478. */
  20479. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20480. var globalPosition = this.getAbsolutePosition();
  20481. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20482. if (!this._collider) {
  20483. this._collider = new BABYLON.Collider();
  20484. }
  20485. this._collider._radius = this.ellipsoid;
  20486. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20487. return this;
  20488. };
  20489. // Submeshes octree
  20490. /**
  20491. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20492. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20493. * @param maxCapacity defines the maximum size of each block (64 by default)
  20494. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20495. * @returns the new octree
  20496. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20497. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20498. */
  20499. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20500. if (maxCapacity === void 0) { maxCapacity = 64; }
  20501. if (maxDepth === void 0) { maxDepth = 2; }
  20502. if (!this._submeshesOctree) {
  20503. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20504. }
  20505. this.computeWorldMatrix(true);
  20506. var boundingInfo = this.getBoundingInfo();
  20507. // Update octree
  20508. var bbox = boundingInfo.boundingBox;
  20509. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20510. return this._submeshesOctree;
  20511. };
  20512. // Collisions
  20513. /** @hidden */
  20514. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20515. this._generatePointsArray();
  20516. if (!this._positions) {
  20517. return this;
  20518. }
  20519. // Transformation
  20520. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20521. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20522. subMesh._lastColliderWorldVertices = [];
  20523. subMesh._trianglePlanes = [];
  20524. var start = subMesh.verticesStart;
  20525. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20526. for (var i = start; i < end; i++) {
  20527. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20528. }
  20529. }
  20530. // Collide
  20531. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20532. if (collider.collisionFound) {
  20533. collider.collidedMesh = this;
  20534. }
  20535. return this;
  20536. };
  20537. /** @hidden */
  20538. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20539. var subMeshes;
  20540. var len;
  20541. // Octrees
  20542. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20543. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20544. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20545. len = intersections.length;
  20546. subMeshes = intersections.data;
  20547. }
  20548. else {
  20549. subMeshes = this.subMeshes;
  20550. len = subMeshes.length;
  20551. }
  20552. for (var index = 0; index < len; index++) {
  20553. var subMesh = subMeshes[index];
  20554. // Bounding test
  20555. if (len > 1 && !subMesh._checkCollision(collider))
  20556. continue;
  20557. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20558. }
  20559. return this;
  20560. };
  20561. /** @hidden */
  20562. AbstractMesh.prototype._checkCollision = function (collider) {
  20563. // Bounding box test
  20564. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20565. return this;
  20566. // Transformation matrix
  20567. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20568. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20569. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20570. return this;
  20571. };
  20572. // Picking
  20573. /** @hidden */
  20574. AbstractMesh.prototype._generatePointsArray = function () {
  20575. return false;
  20576. };
  20577. /**
  20578. * Checks if the passed Ray intersects with the mesh
  20579. * @param ray defines the ray to use
  20580. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20581. * @returns the picking info
  20582. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20583. */
  20584. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20585. var pickingInfo = new BABYLON.PickingInfo();
  20586. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20587. return pickingInfo;
  20588. }
  20589. if (!this._generatePointsArray()) {
  20590. return pickingInfo;
  20591. }
  20592. var intersectInfo = null;
  20593. // Octrees
  20594. var subMeshes;
  20595. var len;
  20596. if (this._submeshesOctree && this.useOctreeForPicking) {
  20597. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20598. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20599. len = intersections.length;
  20600. subMeshes = intersections.data;
  20601. }
  20602. else {
  20603. subMeshes = this.subMeshes;
  20604. len = subMeshes.length;
  20605. }
  20606. for (var index = 0; index < len; index++) {
  20607. var subMesh = subMeshes[index];
  20608. // Bounding test
  20609. if (len > 1 && !subMesh.canIntersects(ray))
  20610. continue;
  20611. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20612. if (currentIntersectInfo) {
  20613. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20614. intersectInfo = currentIntersectInfo;
  20615. intersectInfo.subMeshId = index;
  20616. if (fastCheck) {
  20617. break;
  20618. }
  20619. }
  20620. }
  20621. }
  20622. if (intersectInfo) {
  20623. // Get picked point
  20624. var world = this.getWorldMatrix();
  20625. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20626. var direction = ray.direction.clone();
  20627. direction = direction.scale(intersectInfo.distance);
  20628. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20629. var pickedPoint = worldOrigin.add(worldDirection);
  20630. // Return result
  20631. pickingInfo.hit = true;
  20632. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20633. pickingInfo.pickedPoint = pickedPoint;
  20634. pickingInfo.pickedMesh = this;
  20635. pickingInfo.bu = intersectInfo.bu || 0;
  20636. pickingInfo.bv = intersectInfo.bv || 0;
  20637. pickingInfo.faceId = intersectInfo.faceId;
  20638. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20639. return pickingInfo;
  20640. }
  20641. return pickingInfo;
  20642. };
  20643. /**
  20644. * Clones the current mesh
  20645. * @param name defines the mesh name
  20646. * @param newParent defines the new mesh parent
  20647. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20648. * @returns the new mesh
  20649. */
  20650. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20651. return null;
  20652. };
  20653. /**
  20654. * Disposes all the submeshes of the current meshnp
  20655. * @returns the current mesh
  20656. */
  20657. AbstractMesh.prototype.releaseSubMeshes = function () {
  20658. if (this.subMeshes) {
  20659. while (this.subMeshes.length) {
  20660. this.subMeshes[0].dispose();
  20661. }
  20662. }
  20663. else {
  20664. this.subMeshes = new Array();
  20665. }
  20666. return this;
  20667. };
  20668. /**
  20669. * Releases resources associated with this abstract mesh.
  20670. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20671. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20672. */
  20673. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20674. var _this = this;
  20675. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20676. var index;
  20677. // Smart Array Retainers.
  20678. this.getScene().freeActiveMeshes();
  20679. this.getScene().freeRenderingGroups();
  20680. // Action manager
  20681. if (this.actionManager !== undefined && this.actionManager !== null) {
  20682. this.actionManager.dispose();
  20683. this.actionManager = null;
  20684. }
  20685. // Skeleton
  20686. this._skeleton = null;
  20687. // Physics
  20688. if (this.physicsImpostor) {
  20689. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20690. }
  20691. // Intersections in progress
  20692. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20693. var other = this._intersectionsInProgress[index];
  20694. var pos = other._intersectionsInProgress.indexOf(this);
  20695. other._intersectionsInProgress.splice(pos, 1);
  20696. }
  20697. this._intersectionsInProgress = [];
  20698. // Lights
  20699. var lights = this.getScene().lights;
  20700. lights.forEach(function (light) {
  20701. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20702. if (meshIndex !== -1) {
  20703. light.includedOnlyMeshes.splice(meshIndex, 1);
  20704. }
  20705. meshIndex = light.excludedMeshes.indexOf(_this);
  20706. if (meshIndex !== -1) {
  20707. light.excludedMeshes.splice(meshIndex, 1);
  20708. }
  20709. // Shadow generators
  20710. var generator = light.getShadowGenerator();
  20711. if (generator) {
  20712. var shadowMap = generator.getShadowMap();
  20713. if (shadowMap && shadowMap.renderList) {
  20714. meshIndex = shadowMap.renderList.indexOf(_this);
  20715. if (meshIndex !== -1) {
  20716. shadowMap.renderList.splice(meshIndex, 1);
  20717. }
  20718. }
  20719. }
  20720. });
  20721. // Edges
  20722. if (this._edgesRenderer) {
  20723. this._edgesRenderer.dispose();
  20724. this._edgesRenderer = null;
  20725. }
  20726. // SubMeshes
  20727. if (this.getClassName() !== "InstancedMesh") {
  20728. this.releaseSubMeshes();
  20729. }
  20730. // Octree
  20731. var sceneOctree = this.getScene().selectionOctree;
  20732. if (sceneOctree !== undefined && sceneOctree !== null) {
  20733. var index = sceneOctree.dynamicContent.indexOf(this);
  20734. if (index !== -1) {
  20735. sceneOctree.dynamicContent.splice(index, 1);
  20736. }
  20737. }
  20738. // Query
  20739. var engine = this.getScene().getEngine();
  20740. if (this._occlusionQuery) {
  20741. this._isOcclusionQueryInProgress = false;
  20742. engine.deleteQuery(this._occlusionQuery);
  20743. this._occlusionQuery = null;
  20744. }
  20745. // Engine
  20746. engine.wipeCaches();
  20747. // Remove from scene
  20748. this.getScene().removeMesh(this);
  20749. if (disposeMaterialAndTextures) {
  20750. if (this.material) {
  20751. this.material.dispose(false, true);
  20752. }
  20753. }
  20754. if (!doNotRecurse) {
  20755. // Particles
  20756. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20757. if (this.getScene().particleSystems[index].emitter === this) {
  20758. this.getScene().particleSystems[index].dispose();
  20759. index--;
  20760. }
  20761. }
  20762. }
  20763. // facet data
  20764. if (this._facetDataEnabled) {
  20765. this.disableFacetData();
  20766. }
  20767. this.onAfterWorldMatrixUpdateObservable.clear();
  20768. this.onCollideObservable.clear();
  20769. this.onCollisionPositionChangeObservable.clear();
  20770. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20771. };
  20772. /**
  20773. * Adds the passed mesh as a child to the current mesh
  20774. * @param mesh defines the child mesh
  20775. * @returns the current mesh
  20776. */
  20777. AbstractMesh.prototype.addChild = function (mesh) {
  20778. mesh.setParent(this);
  20779. return this;
  20780. };
  20781. /**
  20782. * Removes the passed mesh from the current mesh children list
  20783. * @param mesh defines the child mesh
  20784. * @returns the current mesh
  20785. */
  20786. AbstractMesh.prototype.removeChild = function (mesh) {
  20787. mesh.setParent(null);
  20788. return this;
  20789. };
  20790. // Facet data
  20791. /** @hidden */
  20792. AbstractMesh.prototype._initFacetData = function () {
  20793. if (!this._facetNormals) {
  20794. this._facetNormals = new Array();
  20795. }
  20796. if (!this._facetPositions) {
  20797. this._facetPositions = new Array();
  20798. }
  20799. if (!this._facetPartitioning) {
  20800. this._facetPartitioning = new Array();
  20801. }
  20802. this._facetNb = (this.getIndices().length / 3) | 0;
  20803. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20804. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20805. for (var f = 0; f < this._facetNb; f++) {
  20806. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20807. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20808. }
  20809. this._facetDataEnabled = true;
  20810. return this;
  20811. };
  20812. /**
  20813. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20814. * This method can be called within the render loop.
  20815. * 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
  20816. * @returns the current mesh
  20817. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20818. */
  20819. AbstractMesh.prototype.updateFacetData = function () {
  20820. if (!this._facetDataEnabled) {
  20821. this._initFacetData();
  20822. }
  20823. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20824. var indices = this.getIndices();
  20825. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20826. var bInfo = this.getBoundingInfo();
  20827. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20828. // init arrays, matrix and sort function on first call
  20829. this._facetDepthSortEnabled = true;
  20830. if (indices instanceof Uint16Array) {
  20831. this._depthSortedIndices = new Uint16Array(indices);
  20832. }
  20833. else if (indices instanceof Uint32Array) {
  20834. this._depthSortedIndices = new Uint32Array(indices);
  20835. }
  20836. else {
  20837. var needs32bits = false;
  20838. for (var i = 0; i < indices.length; i++) {
  20839. if (indices[i] > 65535) {
  20840. needs32bits = true;
  20841. break;
  20842. }
  20843. }
  20844. if (needs32bits) {
  20845. this._depthSortedIndices = new Uint32Array(indices);
  20846. }
  20847. else {
  20848. this._depthSortedIndices = new Uint16Array(indices);
  20849. }
  20850. }
  20851. this._facetDepthSortFunction = function (f1, f2) {
  20852. return (f2.sqDistance - f1.sqDistance);
  20853. };
  20854. if (!this._facetDepthSortFrom) {
  20855. var camera = this.getScene().activeCamera;
  20856. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20857. }
  20858. this._depthSortedFacets = [];
  20859. for (var f = 0; f < this._facetNb; f++) {
  20860. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20861. this._depthSortedFacets.push(depthSortedFacet);
  20862. }
  20863. this._invertedMatrix = BABYLON.Matrix.Identity();
  20864. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20865. }
  20866. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20867. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20868. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20869. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20870. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20871. this._subDiv.max = this._partitioningSubdivisions;
  20872. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20873. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20874. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20875. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20876. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20877. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20878. // set the parameters for ComputeNormals()
  20879. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20880. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20881. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20882. this._facetParameters.bInfo = bInfo;
  20883. this._facetParameters.bbSize = this._bbSize;
  20884. this._facetParameters.subDiv = this._subDiv;
  20885. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20886. this._facetParameters.depthSort = this._facetDepthSort;
  20887. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20888. this.computeWorldMatrix(true);
  20889. this._worldMatrix.invertToRef(this._invertedMatrix);
  20890. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20891. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20892. }
  20893. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20894. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20895. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20896. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20897. var l = (this._depthSortedIndices.length / 3) | 0;
  20898. for (var f = 0; f < l; f++) {
  20899. var sind = this._depthSortedFacets[f].ind;
  20900. this._depthSortedIndices[f * 3] = indices[sind];
  20901. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20902. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20903. }
  20904. this.updateIndices(this._depthSortedIndices);
  20905. }
  20906. return this;
  20907. };
  20908. /**
  20909. * Returns the facetLocalNormals array.
  20910. * The normals are expressed in the mesh local spac
  20911. * @returns an array of Vector3
  20912. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20913. */
  20914. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20915. if (!this._facetNormals) {
  20916. this.updateFacetData();
  20917. }
  20918. return this._facetNormals;
  20919. };
  20920. /**
  20921. * Returns the facetLocalPositions array.
  20922. * The facet positions are expressed in the mesh local space
  20923. * @returns an array of Vector3
  20924. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20925. */
  20926. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20927. if (!this._facetPositions) {
  20928. this.updateFacetData();
  20929. }
  20930. return this._facetPositions;
  20931. };
  20932. /**
  20933. * Returns the facetLocalPartioning array
  20934. * @returns an array of array of numbers
  20935. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20936. */
  20937. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20938. if (!this._facetPartitioning) {
  20939. this.updateFacetData();
  20940. }
  20941. return this._facetPartitioning;
  20942. };
  20943. /**
  20944. * Returns the i-th facet position in the world system.
  20945. * This method allocates a new Vector3 per call
  20946. * @param i defines the facet index
  20947. * @returns a new Vector3
  20948. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20949. */
  20950. AbstractMesh.prototype.getFacetPosition = function (i) {
  20951. var pos = BABYLON.Vector3.Zero();
  20952. this.getFacetPositionToRef(i, pos);
  20953. return pos;
  20954. };
  20955. /**
  20956. * Sets the reference Vector3 with the i-th facet position in the world system
  20957. * @param i defines the facet index
  20958. * @param ref defines the target vector
  20959. * @returns the current mesh
  20960. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20961. */
  20962. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20963. var localPos = (this.getFacetLocalPositions())[i];
  20964. var world = this.getWorldMatrix();
  20965. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20966. return this;
  20967. };
  20968. /**
  20969. * Returns the i-th facet normal in the world system.
  20970. * This method allocates a new Vector3 per call
  20971. * @param i defines the facet index
  20972. * @returns a new Vector3
  20973. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20974. */
  20975. AbstractMesh.prototype.getFacetNormal = function (i) {
  20976. var norm = BABYLON.Vector3.Zero();
  20977. this.getFacetNormalToRef(i, norm);
  20978. return norm;
  20979. };
  20980. /**
  20981. * Sets the reference Vector3 with the i-th facet normal in the world system
  20982. * @param i defines the facet index
  20983. * @param ref defines the target vector
  20984. * @returns the current mesh
  20985. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20986. */
  20987. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20988. var localNorm = (this.getFacetLocalNormals())[i];
  20989. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20990. return this;
  20991. };
  20992. /**
  20993. * 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)
  20994. * @param x defines x coordinate
  20995. * @param y defines y coordinate
  20996. * @param z defines z coordinate
  20997. * @returns the array of facet indexes
  20998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20999. */
  21000. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21001. var bInfo = this.getBoundingInfo();
  21002. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21003. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21004. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21005. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21006. return null;
  21007. }
  21008. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21009. };
  21010. /**
  21011. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21012. * @param projected sets as the (x,y,z) world projection on the facet
  21013. * @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
  21014. * @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
  21015. * @param x defines x coordinate
  21016. * @param y defines y coordinate
  21017. * @param z defines z coordinate
  21018. * @returns the face index if found (or null instead)
  21019. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21020. */
  21021. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21022. if (checkFace === void 0) { checkFace = false; }
  21023. if (facing === void 0) { facing = true; }
  21024. var world = this.getWorldMatrix();
  21025. var invMat = BABYLON.Tmp.Matrix[5];
  21026. world.invertToRef(invMat);
  21027. var invVect = BABYLON.Tmp.Vector3[8];
  21028. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21029. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21030. if (projected) {
  21031. // tranform the local computed projected vector to world coordinates
  21032. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21033. }
  21034. return closest;
  21035. };
  21036. /**
  21037. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21038. * @param projected sets as the (x,y,z) local projection on the facet
  21039. * @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
  21040. * @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
  21041. * @param x defines x coordinate
  21042. * @param y defines y coordinate
  21043. * @param z defines z coordinate
  21044. * @returns the face index if found (or null instead)
  21045. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21046. */
  21047. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21048. if (checkFace === void 0) { checkFace = false; }
  21049. if (facing === void 0) { facing = true; }
  21050. var closest = null;
  21051. var tmpx = 0.0;
  21052. var tmpy = 0.0;
  21053. var tmpz = 0.0;
  21054. var d = 0.0; // tmp dot facet normal * facet position
  21055. var t0 = 0.0;
  21056. var projx = 0.0;
  21057. var projy = 0.0;
  21058. var projz = 0.0;
  21059. // Get all the facets in the same partitioning block than (x, y, z)
  21060. var facetPositions = this.getFacetLocalPositions();
  21061. var facetNormals = this.getFacetLocalNormals();
  21062. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21063. if (!facetsInBlock) {
  21064. return null;
  21065. }
  21066. // Get the closest facet to (x, y, z)
  21067. var shortest = Number.MAX_VALUE; // init distance vars
  21068. var tmpDistance = shortest;
  21069. var fib; // current facet in the block
  21070. var norm; // current facet normal
  21071. var p0; // current facet barycenter position
  21072. // loop on all the facets in the current partitioning block
  21073. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21074. fib = facetsInBlock[idx];
  21075. norm = facetNormals[fib];
  21076. p0 = facetPositions[fib];
  21077. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21078. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21079. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21080. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21081. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21082. projx = x + norm.x * t0;
  21083. projy = y + norm.y * t0;
  21084. projz = z + norm.z * t0;
  21085. tmpx = projx - x;
  21086. tmpy = projy - y;
  21087. tmpz = projz - z;
  21088. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21089. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21090. shortest = tmpDistance;
  21091. closest = fib;
  21092. if (projected) {
  21093. projected.x = projx;
  21094. projected.y = projy;
  21095. projected.z = projz;
  21096. }
  21097. }
  21098. }
  21099. }
  21100. return closest;
  21101. };
  21102. /**
  21103. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21104. * @returns the parameters
  21105. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21106. */
  21107. AbstractMesh.prototype.getFacetDataParameters = function () {
  21108. return this._facetParameters;
  21109. };
  21110. /**
  21111. * Disables the feature FacetData and frees the related memory
  21112. * @returns the current mesh
  21113. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21114. */
  21115. AbstractMesh.prototype.disableFacetData = function () {
  21116. if (this._facetDataEnabled) {
  21117. this._facetDataEnabled = false;
  21118. this._facetPositions = new Array();
  21119. this._facetNormals = new Array();
  21120. this._facetPartitioning = new Array();
  21121. this._facetParameters = null;
  21122. this._depthSortedIndices = new Uint32Array(0);
  21123. }
  21124. return this;
  21125. };
  21126. /**
  21127. * Updates the AbstractMesh indices array
  21128. * @param indices defines the data source
  21129. * @returns the current mesh
  21130. */
  21131. AbstractMesh.prototype.updateIndices = function (indices) {
  21132. return this;
  21133. };
  21134. /**
  21135. * Creates new normals data for the mesh
  21136. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21137. * @returns the current mesh
  21138. */
  21139. AbstractMesh.prototype.createNormals = function (updatable) {
  21140. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21141. var indices = this.getIndices();
  21142. var normals;
  21143. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21144. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21145. }
  21146. else {
  21147. normals = [];
  21148. }
  21149. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21150. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21151. return this;
  21152. };
  21153. /**
  21154. * Align the mesh with a normal
  21155. * @param normal defines the normal to use
  21156. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21157. * @returns the current mesh
  21158. */
  21159. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21160. if (!upDirection) {
  21161. upDirection = BABYLON.Axis.Y;
  21162. }
  21163. var axisX = BABYLON.Tmp.Vector3[0];
  21164. var axisZ = BABYLON.Tmp.Vector3[1];
  21165. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21166. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21167. if (this.rotationQuaternion) {
  21168. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21169. }
  21170. else {
  21171. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21172. }
  21173. return this;
  21174. };
  21175. /** @hidden */
  21176. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21177. var engine = this.getEngine();
  21178. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21179. this._isOccluded = false;
  21180. return;
  21181. }
  21182. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21183. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21184. if (isOcclusionQueryAvailable) {
  21185. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21186. this._isOcclusionQueryInProgress = false;
  21187. this._occlusionInternalRetryCounter = 0;
  21188. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21189. }
  21190. else {
  21191. this._occlusionInternalRetryCounter++;
  21192. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21193. this._isOcclusionQueryInProgress = false;
  21194. this._occlusionInternalRetryCounter = 0;
  21195. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21196. // if strict continue the last state of the object.
  21197. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21198. }
  21199. else {
  21200. return;
  21201. }
  21202. }
  21203. }
  21204. var scene = this.getScene();
  21205. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21206. if (!this._occlusionQuery) {
  21207. this._occlusionQuery = engine.createQuery();
  21208. }
  21209. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21210. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21211. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21212. this._isOcclusionQueryInProgress = true;
  21213. };
  21214. /** No occlusion */
  21215. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21216. /** Occlusion set to optimisitic */
  21217. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21218. /** Occlusion set to strict */
  21219. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21220. /** Use an accurante occlusion algorithm */
  21221. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21222. /** Use a conservative occlusion algorithm */
  21223. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21224. return AbstractMesh;
  21225. }(BABYLON.TransformNode));
  21226. BABYLON.AbstractMesh = AbstractMesh;
  21227. })(BABYLON || (BABYLON = {}));
  21228. //# sourceMappingURL=babylon.abstractMesh.js.map
  21229. var BABYLON;
  21230. (function (BABYLON) {
  21231. /**
  21232. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21233. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21234. * 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.
  21235. */
  21236. var Light = /** @class */ (function (_super) {
  21237. __extends(Light, _super);
  21238. /**
  21239. * Creates a Light object in the scene.
  21240. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21241. * @param name The firendly name of the light
  21242. * @param scene The scene the light belongs too
  21243. */
  21244. function Light(name, scene) {
  21245. var _this = _super.call(this, name, scene) || this;
  21246. /**
  21247. * Diffuse gives the basic color to an object.
  21248. */
  21249. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21250. /**
  21251. * Specular produces a highlight color on an object.
  21252. * Note: This is note affecting PBR materials.
  21253. */
  21254. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21255. /**
  21256. * Strength of the light.
  21257. * Note: By default it is define in the framework own unit.
  21258. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21259. */
  21260. _this.intensity = 1.0;
  21261. /**
  21262. * Defines how far from the source the light is impacting in scene units.
  21263. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21264. */
  21265. _this.range = Number.MAX_VALUE;
  21266. /**
  21267. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21268. * of light.
  21269. */
  21270. _this._photometricScale = 1.0;
  21271. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21272. _this._radius = 0.00001;
  21273. /**
  21274. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21275. * exceeding the number allowed of the materials.
  21276. */
  21277. _this.renderPriority = 0;
  21278. _this._shadowEnabled = true;
  21279. _this._excludeWithLayerMask = 0;
  21280. _this._includeOnlyWithLayerMask = 0;
  21281. _this._lightmapMode = 0;
  21282. /**
  21283. * @hidden Internal use only.
  21284. */
  21285. _this._excludedMeshesIds = new Array();
  21286. /**
  21287. * @hidden Internal use only.
  21288. */
  21289. _this._includedOnlyMeshesIds = new Array();
  21290. _this.getScene().addLight(_this);
  21291. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21292. _this._buildUniformLayout();
  21293. _this.includedOnlyMeshes = new Array();
  21294. _this.excludedMeshes = new Array();
  21295. _this._resyncMeshes();
  21296. return _this;
  21297. }
  21298. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21299. /**
  21300. * If every light affecting the material is in this lightmapMode,
  21301. * material.lightmapTexture adds or multiplies
  21302. * (depends on material.useLightmapAsShadowmap)
  21303. * after every other light calculations.
  21304. */
  21305. get: function () {
  21306. return Light._LIGHTMAP_DEFAULT;
  21307. },
  21308. enumerable: true,
  21309. configurable: true
  21310. });
  21311. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21312. /**
  21313. * material.lightmapTexture as only diffuse lighting from this light
  21314. * adds only specular lighting from this light
  21315. * adds dynamic shadows
  21316. */
  21317. get: function () {
  21318. return Light._LIGHTMAP_SPECULAR;
  21319. },
  21320. enumerable: true,
  21321. configurable: true
  21322. });
  21323. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21324. /**
  21325. * material.lightmapTexture as only lighting
  21326. * no light calculation from this light
  21327. * only adds dynamic shadows from this light
  21328. */
  21329. get: function () {
  21330. return Light._LIGHTMAP_SHADOWSONLY;
  21331. },
  21332. enumerable: true,
  21333. configurable: true
  21334. });
  21335. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21336. /**
  21337. * Each light type uses the default quantity according to its type:
  21338. * point/spot lights use luminous intensity
  21339. * directional lights use illuminance
  21340. */
  21341. get: function () {
  21342. return Light._INTENSITYMODE_AUTOMATIC;
  21343. },
  21344. enumerable: true,
  21345. configurable: true
  21346. });
  21347. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21348. /**
  21349. * lumen (lm)
  21350. */
  21351. get: function () {
  21352. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21353. },
  21354. enumerable: true,
  21355. configurable: true
  21356. });
  21357. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21358. /**
  21359. * candela (lm/sr)
  21360. */
  21361. get: function () {
  21362. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21368. /**
  21369. * lux (lm/m^2)
  21370. */
  21371. get: function () {
  21372. return Light._INTENSITYMODE_ILLUMINANCE;
  21373. },
  21374. enumerable: true,
  21375. configurable: true
  21376. });
  21377. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21378. /**
  21379. * nit (cd/m^2)
  21380. */
  21381. get: function () {
  21382. return Light._INTENSITYMODE_LUMINANCE;
  21383. },
  21384. enumerable: true,
  21385. configurable: true
  21386. });
  21387. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21388. /**
  21389. * Light type const id of the point light.
  21390. */
  21391. get: function () {
  21392. return Light._LIGHTTYPEID_POINTLIGHT;
  21393. },
  21394. enumerable: true,
  21395. configurable: true
  21396. });
  21397. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21398. /**
  21399. * Light type const id of the directional light.
  21400. */
  21401. get: function () {
  21402. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21403. },
  21404. enumerable: true,
  21405. configurable: true
  21406. });
  21407. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21408. /**
  21409. * Light type const id of the spot light.
  21410. */
  21411. get: function () {
  21412. return Light._LIGHTTYPEID_SPOTLIGHT;
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21418. /**
  21419. * Light type const id of the hemispheric light.
  21420. */
  21421. get: function () {
  21422. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light.prototype, "intensityMode", {
  21428. /**
  21429. * Gets the photometric scale used to interpret the intensity.
  21430. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21431. */
  21432. get: function () {
  21433. return this._intensityMode;
  21434. },
  21435. /**
  21436. * Sets the photometric scale used to interpret the intensity.
  21437. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21438. */
  21439. set: function (value) {
  21440. this._intensityMode = value;
  21441. this._computePhotometricScale();
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. ;
  21447. ;
  21448. Object.defineProperty(Light.prototype, "radius", {
  21449. /**
  21450. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21451. */
  21452. get: function () {
  21453. return this._radius;
  21454. },
  21455. /**
  21456. * sets the light radius used by PBR Materials to simulate soft area lights.
  21457. */
  21458. set: function (value) {
  21459. this._radius = value;
  21460. this._computePhotometricScale();
  21461. },
  21462. enumerable: true,
  21463. configurable: true
  21464. });
  21465. ;
  21466. ;
  21467. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21468. /**
  21469. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21470. * the current shadow generator.
  21471. */
  21472. get: function () {
  21473. return this._shadowEnabled;
  21474. },
  21475. /**
  21476. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21477. * the current shadow generator.
  21478. */
  21479. set: function (value) {
  21480. if (this._shadowEnabled === value) {
  21481. return;
  21482. }
  21483. this._shadowEnabled = value;
  21484. this._markMeshesAsLightDirty();
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21490. /**
  21491. * Gets the only meshes impacted by this light.
  21492. */
  21493. get: function () {
  21494. return this._includedOnlyMeshes;
  21495. },
  21496. /**
  21497. * Sets the only meshes impacted by this light.
  21498. */
  21499. set: function (value) {
  21500. this._includedOnlyMeshes = value;
  21501. this._hookArrayForIncludedOnly(value);
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21507. /**
  21508. * Gets the meshes not impacted by this light.
  21509. */
  21510. get: function () {
  21511. return this._excludedMeshes;
  21512. },
  21513. /**
  21514. * Sets the meshes not impacted by this light.
  21515. */
  21516. set: function (value) {
  21517. this._excludedMeshes = value;
  21518. this._hookArrayForExcluded(value);
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21524. /**
  21525. * Gets the layer id use to find what meshes are not impacted by the light.
  21526. * Inactive if 0
  21527. */
  21528. get: function () {
  21529. return this._excludeWithLayerMask;
  21530. },
  21531. /**
  21532. * Sets the layer id use to find what meshes are not impacted by the light.
  21533. * Inactive if 0
  21534. */
  21535. set: function (value) {
  21536. this._excludeWithLayerMask = value;
  21537. this._resyncMeshes();
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21543. /**
  21544. * Gets the layer id use to find what meshes are impacted by the light.
  21545. * Inactive if 0
  21546. */
  21547. get: function () {
  21548. return this._includeOnlyWithLayerMask;
  21549. },
  21550. /**
  21551. * Sets the layer id use to find what meshes are impacted by the light.
  21552. * Inactive if 0
  21553. */
  21554. set: function (value) {
  21555. this._includeOnlyWithLayerMask = value;
  21556. this._resyncMeshes();
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. Object.defineProperty(Light.prototype, "lightmapMode", {
  21562. /**
  21563. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21564. */
  21565. get: function () {
  21566. return this._lightmapMode;
  21567. },
  21568. /**
  21569. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21570. */
  21571. set: function (value) {
  21572. if (this._lightmapMode === value) {
  21573. return;
  21574. }
  21575. this._lightmapMode = value;
  21576. this._markMeshesAsLightDirty();
  21577. },
  21578. enumerable: true,
  21579. configurable: true
  21580. });
  21581. /**
  21582. * Returns the string "Light".
  21583. * @returns the class name
  21584. */
  21585. Light.prototype.getClassName = function () {
  21586. return "Light";
  21587. };
  21588. /**
  21589. * Converts the light information to a readable string for debug purpose.
  21590. * @param fullDetails Supports for multiple levels of logging within scene loading
  21591. * @returns the human readable light info
  21592. */
  21593. Light.prototype.toString = function (fullDetails) {
  21594. var ret = "Name: " + this.name;
  21595. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21596. if (this.animations) {
  21597. for (var i = 0; i < this.animations.length; i++) {
  21598. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21599. }
  21600. }
  21601. if (fullDetails) {
  21602. }
  21603. return ret;
  21604. };
  21605. /**
  21606. * Set the enabled state of this node.
  21607. * @param value - the new enabled state
  21608. */
  21609. Light.prototype.setEnabled = function (value) {
  21610. _super.prototype.setEnabled.call(this, value);
  21611. this._resyncMeshes();
  21612. };
  21613. /**
  21614. * Returns the Light associated shadow generator if any.
  21615. * @return the associated shadow generator.
  21616. */
  21617. Light.prototype.getShadowGenerator = function () {
  21618. return this._shadowGenerator;
  21619. };
  21620. /**
  21621. * Returns a Vector3, the absolute light position in the World.
  21622. * @returns the world space position of the light
  21623. */
  21624. Light.prototype.getAbsolutePosition = function () {
  21625. return BABYLON.Vector3.Zero();
  21626. };
  21627. /**
  21628. * Specifies if the light will affect the passed mesh.
  21629. * @param mesh The mesh to test against the light
  21630. * @return true the mesh is affected otherwise, false.
  21631. */
  21632. Light.prototype.canAffectMesh = function (mesh) {
  21633. if (!mesh) {
  21634. return true;
  21635. }
  21636. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21637. return false;
  21638. }
  21639. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21640. return false;
  21641. }
  21642. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21643. return false;
  21644. }
  21645. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21646. return false;
  21647. }
  21648. return true;
  21649. };
  21650. /**
  21651. * Computes and Returns the light World matrix.
  21652. * @returns the world matrix
  21653. */
  21654. Light.prototype.getWorldMatrix = function () {
  21655. this._currentRenderId = this.getScene().getRenderId();
  21656. this._childRenderId = this._currentRenderId;
  21657. var worldMatrix = this._getWorldMatrix();
  21658. if (this.parent && this.parent.getWorldMatrix) {
  21659. if (!this._parentedWorldMatrix) {
  21660. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21661. }
  21662. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21663. this._markSyncedWithParent();
  21664. return this._parentedWorldMatrix;
  21665. }
  21666. return worldMatrix;
  21667. };
  21668. /**
  21669. * Sort function to order lights for rendering.
  21670. * @param a First Light object to compare to second.
  21671. * @param b Second Light object to compare first.
  21672. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21673. */
  21674. Light.CompareLightsPriority = function (a, b) {
  21675. //shadow-casting lights have priority over non-shadow-casting lights
  21676. //the renderPrioirty is a secondary sort criterion
  21677. if (a.shadowEnabled !== b.shadowEnabled) {
  21678. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21679. }
  21680. return b.renderPriority - a.renderPriority;
  21681. };
  21682. /**
  21683. * Releases resources associated with this node.
  21684. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21685. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21686. */
  21687. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21688. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21689. if (this._shadowGenerator) {
  21690. this._shadowGenerator.dispose();
  21691. this._shadowGenerator = null;
  21692. }
  21693. // Animations
  21694. this.getScene().stopAnimation(this);
  21695. // Remove from meshes
  21696. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21697. var mesh = _a[_i];
  21698. mesh._removeLightSource(this);
  21699. }
  21700. this._uniformBuffer.dispose();
  21701. // Remove from scene
  21702. this.getScene().removeLight(this);
  21703. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21704. };
  21705. /**
  21706. * Returns the light type ID (integer).
  21707. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21708. */
  21709. Light.prototype.getTypeID = function () {
  21710. return 0;
  21711. };
  21712. /**
  21713. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21714. * @returns the scaled intensity in intensity mode unit
  21715. */
  21716. Light.prototype.getScaledIntensity = function () {
  21717. return this._photometricScale * this.intensity;
  21718. };
  21719. /**
  21720. * Returns a new Light object, named "name", from the current one.
  21721. * @param name The name of the cloned light
  21722. * @returns the new created light
  21723. */
  21724. Light.prototype.clone = function (name) {
  21725. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21726. if (!constructor) {
  21727. return null;
  21728. }
  21729. return BABYLON.SerializationHelper.Clone(constructor, this);
  21730. };
  21731. /**
  21732. * Serializes the current light into a Serialization object.
  21733. * @returns the serialized object.
  21734. */
  21735. Light.prototype.serialize = function () {
  21736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21737. // Type
  21738. serializationObject.type = this.getTypeID();
  21739. // Parent
  21740. if (this.parent) {
  21741. serializationObject.parentId = this.parent.id;
  21742. }
  21743. // Inclusion / exclusions
  21744. if (this.excludedMeshes.length > 0) {
  21745. serializationObject.excludedMeshesIds = [];
  21746. this.excludedMeshes.forEach(function (mesh) {
  21747. serializationObject.excludedMeshesIds.push(mesh.id);
  21748. });
  21749. }
  21750. if (this.includedOnlyMeshes.length > 0) {
  21751. serializationObject.includedOnlyMeshesIds = [];
  21752. this.includedOnlyMeshes.forEach(function (mesh) {
  21753. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21754. });
  21755. }
  21756. // Animations
  21757. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21758. serializationObject.ranges = this.serializeAnimationRanges();
  21759. return serializationObject;
  21760. };
  21761. /**
  21762. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21763. * This new light is named "name" and added to the passed scene.
  21764. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21765. * @param name The friendly name of the light
  21766. * @param scene The scene the new light will belong to
  21767. * @returns the constructor function
  21768. */
  21769. Light.GetConstructorFromName = function (type, name, scene) {
  21770. switch (type) {
  21771. case 0:
  21772. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21773. case 1:
  21774. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21775. case 2:
  21776. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21777. case 3:
  21778. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21779. }
  21780. return null;
  21781. };
  21782. /**
  21783. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21784. * @param parsedLight The JSON representation of the light
  21785. * @param scene The scene to create the parsed light in
  21786. * @returns the created light after parsing
  21787. */
  21788. Light.Parse = function (parsedLight, scene) {
  21789. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21790. if (!constructor) {
  21791. return null;
  21792. }
  21793. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21794. // Inclusion / exclusions
  21795. if (parsedLight.excludedMeshesIds) {
  21796. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21797. }
  21798. if (parsedLight.includedOnlyMeshesIds) {
  21799. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21800. }
  21801. // Parent
  21802. if (parsedLight.parentId) {
  21803. light._waitingParentId = parsedLight.parentId;
  21804. }
  21805. // Animations
  21806. if (parsedLight.animations) {
  21807. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21808. var parsedAnimation = parsedLight.animations[animationIndex];
  21809. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21810. }
  21811. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21812. }
  21813. if (parsedLight.autoAnimate) {
  21814. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21815. }
  21816. return light;
  21817. };
  21818. Light.prototype._hookArrayForExcluded = function (array) {
  21819. var _this = this;
  21820. var oldPush = array.push;
  21821. array.push = function () {
  21822. var items = [];
  21823. for (var _i = 0; _i < arguments.length; _i++) {
  21824. items[_i] = arguments[_i];
  21825. }
  21826. var result = oldPush.apply(array, items);
  21827. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21828. var item = items_1[_a];
  21829. item._resyncLighSource(_this);
  21830. }
  21831. return result;
  21832. };
  21833. var oldSplice = array.splice;
  21834. array.splice = function (index, deleteCount) {
  21835. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21836. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21837. var item = deleted_1[_i];
  21838. item._resyncLighSource(_this);
  21839. }
  21840. return deleted;
  21841. };
  21842. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21843. var item = array_1[_i];
  21844. item._resyncLighSource(this);
  21845. }
  21846. };
  21847. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21848. var _this = this;
  21849. var oldPush = array.push;
  21850. array.push = function () {
  21851. var items = [];
  21852. for (var _i = 0; _i < arguments.length; _i++) {
  21853. items[_i] = arguments[_i];
  21854. }
  21855. var result = oldPush.apply(array, items);
  21856. _this._resyncMeshes();
  21857. return result;
  21858. };
  21859. var oldSplice = array.splice;
  21860. array.splice = function (index, deleteCount) {
  21861. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21862. _this._resyncMeshes();
  21863. return deleted;
  21864. };
  21865. this._resyncMeshes();
  21866. };
  21867. Light.prototype._resyncMeshes = function () {
  21868. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21869. var mesh = _a[_i];
  21870. mesh._resyncLighSource(this);
  21871. }
  21872. };
  21873. /**
  21874. * Forces the meshes to update their light related information in their rendering used effects
  21875. * @hidden Internal Use Only
  21876. */
  21877. Light.prototype._markMeshesAsLightDirty = function () {
  21878. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21879. var mesh = _a[_i];
  21880. if (mesh._lightSources.indexOf(this) !== -1) {
  21881. mesh._markSubMeshesAsLightDirty();
  21882. }
  21883. }
  21884. };
  21885. /**
  21886. * Recomputes the cached photometric scale if needed.
  21887. */
  21888. Light.prototype._computePhotometricScale = function () {
  21889. this._photometricScale = this._getPhotometricScale();
  21890. this.getScene().resetCachedMaterial();
  21891. };
  21892. /**
  21893. * Returns the Photometric Scale according to the light type and intensity mode.
  21894. */
  21895. Light.prototype._getPhotometricScale = function () {
  21896. var photometricScale = 0.0;
  21897. var lightTypeID = this.getTypeID();
  21898. //get photometric mode
  21899. var photometricMode = this.intensityMode;
  21900. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21901. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21902. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21903. }
  21904. else {
  21905. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21906. }
  21907. }
  21908. //compute photometric scale
  21909. switch (lightTypeID) {
  21910. case Light.LIGHTTYPEID_POINTLIGHT:
  21911. case Light.LIGHTTYPEID_SPOTLIGHT:
  21912. switch (photometricMode) {
  21913. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21914. photometricScale = 1.0 / (4.0 * Math.PI);
  21915. break;
  21916. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21917. photometricScale = 1.0;
  21918. break;
  21919. case Light.INTENSITYMODE_LUMINANCE:
  21920. photometricScale = this.radius * this.radius;
  21921. break;
  21922. }
  21923. break;
  21924. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21925. switch (photometricMode) {
  21926. case Light.INTENSITYMODE_ILLUMINANCE:
  21927. photometricScale = 1.0;
  21928. break;
  21929. case Light.INTENSITYMODE_LUMINANCE:
  21930. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21931. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21932. var apexAngleRadians = this.radius;
  21933. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21934. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21935. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21936. photometricScale = solidAngle;
  21937. break;
  21938. }
  21939. break;
  21940. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21941. // No fall off in hemisperic light.
  21942. photometricScale = 1.0;
  21943. break;
  21944. }
  21945. return photometricScale;
  21946. };
  21947. /**
  21948. * Reorder the light in the scene according to their defined priority.
  21949. * @hidden Internal Use Only
  21950. */
  21951. Light.prototype._reorderLightsInScene = function () {
  21952. var scene = this.getScene();
  21953. if (this._renderPriority != 0) {
  21954. scene.requireLightSorting = true;
  21955. }
  21956. this.getScene().sortLightsByPriority();
  21957. };
  21958. //lightmapMode Consts
  21959. Light._LIGHTMAP_DEFAULT = 0;
  21960. Light._LIGHTMAP_SPECULAR = 1;
  21961. Light._LIGHTMAP_SHADOWSONLY = 2;
  21962. // Intensity Mode Consts
  21963. Light._INTENSITYMODE_AUTOMATIC = 0;
  21964. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21965. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21966. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21967. Light._INTENSITYMODE_LUMINANCE = 4;
  21968. // Light types ids const.
  21969. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21970. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21971. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21972. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21973. __decorate([
  21974. BABYLON.serializeAsColor3()
  21975. ], Light.prototype, "diffuse", void 0);
  21976. __decorate([
  21977. BABYLON.serializeAsColor3()
  21978. ], Light.prototype, "specular", void 0);
  21979. __decorate([
  21980. BABYLON.serialize()
  21981. ], Light.prototype, "intensity", void 0);
  21982. __decorate([
  21983. BABYLON.serialize()
  21984. ], Light.prototype, "range", void 0);
  21985. __decorate([
  21986. BABYLON.serialize()
  21987. ], Light.prototype, "intensityMode", null);
  21988. __decorate([
  21989. BABYLON.serialize()
  21990. ], Light.prototype, "radius", null);
  21991. __decorate([
  21992. BABYLON.serialize()
  21993. ], Light.prototype, "_renderPriority", void 0);
  21994. __decorate([
  21995. BABYLON.expandToProperty("_reorderLightsInScene")
  21996. ], Light.prototype, "renderPriority", void 0);
  21997. __decorate([
  21998. BABYLON.serialize("shadowEnabled")
  21999. ], Light.prototype, "_shadowEnabled", void 0);
  22000. __decorate([
  22001. BABYLON.serialize("excludeWithLayerMask")
  22002. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22003. __decorate([
  22004. BABYLON.serialize("includeOnlyWithLayerMask")
  22005. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22006. __decorate([
  22007. BABYLON.serialize("lightmapMode")
  22008. ], Light.prototype, "_lightmapMode", void 0);
  22009. return Light;
  22010. }(BABYLON.Node));
  22011. BABYLON.Light = Light;
  22012. })(BABYLON || (BABYLON = {}));
  22013. //# sourceMappingURL=babylon.light.js.map
  22014. var BABYLON;
  22015. (function (BABYLON) {
  22016. var Camera = /** @class */ (function (_super) {
  22017. __extends(Camera, _super);
  22018. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22019. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22020. var _this = _super.call(this, name, scene) || this;
  22021. /**
  22022. * The vector the camera should consider as up.
  22023. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22024. */
  22025. _this.upVector = BABYLON.Vector3.Up();
  22026. _this.orthoLeft = null;
  22027. _this.orthoRight = null;
  22028. _this.orthoBottom = null;
  22029. _this.orthoTop = null;
  22030. /**
  22031. * FOV is set in Radians. (default is 0.8)
  22032. */
  22033. _this.fov = 0.8;
  22034. _this.minZ = 1;
  22035. _this.maxZ = 10000.0;
  22036. _this.inertia = 0.9;
  22037. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22038. _this.isIntermediate = false;
  22039. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22040. /**
  22041. * Restricts the camera to viewing objects with the same layerMask.
  22042. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22043. */
  22044. _this.layerMask = 0x0FFFFFFF;
  22045. /**
  22046. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22047. */
  22048. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22049. // Camera rig members
  22050. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22051. _this._rigCameras = new Array();
  22052. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22053. _this._skipRendering = false;
  22054. _this.customRenderTargets = new Array();
  22055. // Observables
  22056. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22057. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22058. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22059. _this.onRestoreStateObservable = new BABYLON.Observable();
  22060. // Cache
  22061. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22062. _this._projectionMatrix = new BABYLON.Matrix();
  22063. _this._doNotComputeProjectionMatrix = false;
  22064. _this._worldMatrix = BABYLON.Matrix.Identity();
  22065. _this._postProcesses = new Array();
  22066. _this._transformMatrix = BABYLON.Matrix.Zero();
  22067. _this._activeMeshes = new BABYLON.SmartArray(256);
  22068. _this._globalPosition = BABYLON.Vector3.Zero();
  22069. _this._refreshFrustumPlanes = true;
  22070. _this.getScene().addCamera(_this);
  22071. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22072. _this.getScene().activeCamera = _this;
  22073. }
  22074. _this.position = position;
  22075. return _this;
  22076. }
  22077. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22078. get: function () {
  22079. return Camera._PERSPECTIVE_CAMERA;
  22080. },
  22081. enumerable: true,
  22082. configurable: true
  22083. });
  22084. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22085. get: function () {
  22086. return Camera._ORTHOGRAPHIC_CAMERA;
  22087. },
  22088. enumerable: true,
  22089. configurable: true
  22090. });
  22091. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22092. /**
  22093. * This is the default FOV mode for perspective cameras.
  22094. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22095. *
  22096. */
  22097. get: function () {
  22098. return Camera._FOVMODE_VERTICAL_FIXED;
  22099. },
  22100. enumerable: true,
  22101. configurable: true
  22102. });
  22103. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22104. /**
  22105. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22106. *
  22107. */
  22108. get: function () {
  22109. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22110. },
  22111. enumerable: true,
  22112. configurable: true
  22113. });
  22114. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22115. get: function () {
  22116. return Camera._RIG_MODE_NONE;
  22117. },
  22118. enumerable: true,
  22119. configurable: true
  22120. });
  22121. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22122. get: function () {
  22123. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22124. },
  22125. enumerable: true,
  22126. configurable: true
  22127. });
  22128. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22129. get: function () {
  22130. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22131. },
  22132. enumerable: true,
  22133. configurable: true
  22134. });
  22135. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22136. get: function () {
  22137. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22138. },
  22139. enumerable: true,
  22140. configurable: true
  22141. });
  22142. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22143. get: function () {
  22144. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22145. },
  22146. enumerable: true,
  22147. configurable: true
  22148. });
  22149. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22150. get: function () {
  22151. return Camera._RIG_MODE_VR;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22157. get: function () {
  22158. return Camera._RIG_MODE_WEBVR;
  22159. },
  22160. enumerable: true,
  22161. configurable: true
  22162. });
  22163. /**
  22164. * Store current camera state (fov, position, etc..)
  22165. */
  22166. Camera.prototype.storeState = function () {
  22167. this._stateStored = true;
  22168. this._storedFov = this.fov;
  22169. return this;
  22170. };
  22171. /**
  22172. * Restores the camera state values if it has been stored. You must call storeState() first
  22173. */
  22174. Camera.prototype._restoreStateValues = function () {
  22175. if (!this._stateStored) {
  22176. return false;
  22177. }
  22178. this.fov = this._storedFov;
  22179. return true;
  22180. };
  22181. /**
  22182. * Restored camera state. You must call storeState() first
  22183. */
  22184. Camera.prototype.restoreState = function () {
  22185. if (this._restoreStateValues()) {
  22186. this.onRestoreStateObservable.notifyObservers(this);
  22187. return true;
  22188. }
  22189. return false;
  22190. };
  22191. Camera.prototype.getClassName = function () {
  22192. return "Camera";
  22193. };
  22194. /**
  22195. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22196. */
  22197. Camera.prototype.toString = function (fullDetails) {
  22198. var ret = "Name: " + this.name;
  22199. ret += ", type: " + this.getClassName();
  22200. if (this.animations) {
  22201. for (var i = 0; i < this.animations.length; i++) {
  22202. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22203. }
  22204. }
  22205. if (fullDetails) {
  22206. }
  22207. return ret;
  22208. };
  22209. Object.defineProperty(Camera.prototype, "globalPosition", {
  22210. get: function () {
  22211. return this._globalPosition;
  22212. },
  22213. enumerable: true,
  22214. configurable: true
  22215. });
  22216. Camera.prototype.getActiveMeshes = function () {
  22217. return this._activeMeshes;
  22218. };
  22219. Camera.prototype.isActiveMesh = function (mesh) {
  22220. return (this._activeMeshes.indexOf(mesh) !== -1);
  22221. };
  22222. /**
  22223. * Is this camera ready to be used/rendered
  22224. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22225. * @return true if the camera is ready
  22226. */
  22227. Camera.prototype.isReady = function (completeCheck) {
  22228. if (completeCheck === void 0) { completeCheck = false; }
  22229. if (completeCheck) {
  22230. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22231. var pp = _a[_i];
  22232. if (pp && !pp.isReady()) {
  22233. return false;
  22234. }
  22235. }
  22236. }
  22237. return _super.prototype.isReady.call(this, completeCheck);
  22238. };
  22239. //Cache
  22240. Camera.prototype._initCache = function () {
  22241. _super.prototype._initCache.call(this);
  22242. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22243. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22244. this._cache.mode = undefined;
  22245. this._cache.minZ = undefined;
  22246. this._cache.maxZ = undefined;
  22247. this._cache.fov = undefined;
  22248. this._cache.fovMode = undefined;
  22249. this._cache.aspectRatio = undefined;
  22250. this._cache.orthoLeft = undefined;
  22251. this._cache.orthoRight = undefined;
  22252. this._cache.orthoBottom = undefined;
  22253. this._cache.orthoTop = undefined;
  22254. this._cache.renderWidth = undefined;
  22255. this._cache.renderHeight = undefined;
  22256. };
  22257. Camera.prototype._updateCache = function (ignoreParentClass) {
  22258. if (!ignoreParentClass) {
  22259. _super.prototype._updateCache.call(this);
  22260. }
  22261. this._cache.position.copyFrom(this.position);
  22262. this._cache.upVector.copyFrom(this.upVector);
  22263. };
  22264. // Synchronized
  22265. Camera.prototype._isSynchronized = function () {
  22266. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22267. };
  22268. Camera.prototype._isSynchronizedViewMatrix = function () {
  22269. if (!_super.prototype._isSynchronized.call(this))
  22270. return false;
  22271. return this._cache.position.equals(this.position)
  22272. && this._cache.upVector.equals(this.upVector)
  22273. && this.isSynchronizedWithParent();
  22274. };
  22275. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22276. var check = this._cache.mode === this.mode
  22277. && this._cache.minZ === this.minZ
  22278. && this._cache.maxZ === this.maxZ;
  22279. if (!check) {
  22280. return false;
  22281. }
  22282. var engine = this.getEngine();
  22283. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22284. check = this._cache.fov === this.fov
  22285. && this._cache.fovMode === this.fovMode
  22286. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22287. }
  22288. else {
  22289. check = this._cache.orthoLeft === this.orthoLeft
  22290. && this._cache.orthoRight === this.orthoRight
  22291. && this._cache.orthoBottom === this.orthoBottom
  22292. && this._cache.orthoTop === this.orthoTop
  22293. && this._cache.renderWidth === engine.getRenderWidth()
  22294. && this._cache.renderHeight === engine.getRenderHeight();
  22295. }
  22296. return check;
  22297. };
  22298. // Controls
  22299. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22300. };
  22301. Camera.prototype.detachControl = function (element) {
  22302. };
  22303. Camera.prototype.update = function () {
  22304. this._checkInputs();
  22305. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22306. this._updateRigCameras();
  22307. }
  22308. };
  22309. Camera.prototype._checkInputs = function () {
  22310. this.onAfterCheckInputsObservable.notifyObservers(this);
  22311. };
  22312. Object.defineProperty(Camera.prototype, "rigCameras", {
  22313. get: function () {
  22314. return this._rigCameras;
  22315. },
  22316. enumerable: true,
  22317. configurable: true
  22318. });
  22319. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22320. get: function () {
  22321. return this._rigPostProcess;
  22322. },
  22323. enumerable: true,
  22324. configurable: true
  22325. });
  22326. /**
  22327. * Internal, gets the first post proces.
  22328. * @returns the first post process to be run on this camera.
  22329. */
  22330. Camera.prototype._getFirstPostProcess = function () {
  22331. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22332. if (this._postProcesses[ppIndex] !== null) {
  22333. return this._postProcesses[ppIndex];
  22334. }
  22335. }
  22336. return null;
  22337. };
  22338. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22339. // invalidate framebuffer
  22340. var firstPostProcess = this._getFirstPostProcess();
  22341. if (firstPostProcess) {
  22342. firstPostProcess.markTextureDirty();
  22343. }
  22344. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22345. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22346. var cam = this._rigCameras[i];
  22347. var rigPostProcess = cam._rigPostProcess;
  22348. // for VR rig, there does not have to be a post process
  22349. if (rigPostProcess) {
  22350. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22351. if (isPass) {
  22352. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22353. cam.isIntermediate = this._postProcesses.length === 0;
  22354. }
  22355. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22356. rigPostProcess.markTextureDirty();
  22357. }
  22358. else {
  22359. cam._postProcesses = this._postProcesses.slice(0);
  22360. }
  22361. }
  22362. };
  22363. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22364. if (insertAt === void 0) { insertAt = null; }
  22365. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22366. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22367. return 0;
  22368. }
  22369. if (insertAt == null || insertAt < 0) {
  22370. this._postProcesses.push(postProcess);
  22371. }
  22372. else if (this._postProcesses[insertAt] === null) {
  22373. this._postProcesses[insertAt] = postProcess;
  22374. }
  22375. else {
  22376. this._postProcesses.splice(insertAt, 0, postProcess);
  22377. }
  22378. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22379. return this._postProcesses.indexOf(postProcess);
  22380. };
  22381. Camera.prototype.detachPostProcess = function (postProcess) {
  22382. var idx = this._postProcesses.indexOf(postProcess);
  22383. if (idx !== -1) {
  22384. this._postProcesses[idx] = null;
  22385. }
  22386. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22387. };
  22388. Camera.prototype.getWorldMatrix = function () {
  22389. if (this._isSynchronizedViewMatrix()) {
  22390. return this._worldMatrix;
  22391. }
  22392. // Getting the the view matrix will also compute the world matrix.
  22393. this.getViewMatrix();
  22394. return this._worldMatrix;
  22395. };
  22396. Camera.prototype._getViewMatrix = function () {
  22397. return BABYLON.Matrix.Identity();
  22398. };
  22399. Camera.prototype.getViewMatrix = function (force) {
  22400. if (!force && this._isSynchronizedViewMatrix()) {
  22401. return this._computedViewMatrix;
  22402. }
  22403. this.updateCache();
  22404. this._computedViewMatrix = this._getViewMatrix();
  22405. this._currentRenderId = this.getScene().getRenderId();
  22406. this._childRenderId = this._currentRenderId;
  22407. this._refreshFrustumPlanes = true;
  22408. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22409. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22410. }
  22411. this.onViewMatrixChangedObservable.notifyObservers(this);
  22412. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22413. return this._computedViewMatrix;
  22414. };
  22415. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22416. this._doNotComputeProjectionMatrix = true;
  22417. if (projection !== undefined) {
  22418. this._projectionMatrix = projection;
  22419. }
  22420. };
  22421. ;
  22422. Camera.prototype.unfreezeProjectionMatrix = function () {
  22423. this._doNotComputeProjectionMatrix = false;
  22424. };
  22425. ;
  22426. Camera.prototype.getProjectionMatrix = function (force) {
  22427. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22428. return this._projectionMatrix;
  22429. }
  22430. // Cache
  22431. this._cache.mode = this.mode;
  22432. this._cache.minZ = this.minZ;
  22433. this._cache.maxZ = this.maxZ;
  22434. // Matrix
  22435. this._refreshFrustumPlanes = true;
  22436. var engine = this.getEngine();
  22437. var scene = this.getScene();
  22438. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22439. this._cache.fov = this.fov;
  22440. this._cache.fovMode = this.fovMode;
  22441. this._cache.aspectRatio = engine.getAspectRatio(this);
  22442. if (this.minZ <= 0) {
  22443. this.minZ = 0.1;
  22444. }
  22445. if (scene.useRightHandedSystem) {
  22446. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22447. }
  22448. else {
  22449. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22450. }
  22451. }
  22452. else {
  22453. var halfWidth = engine.getRenderWidth() / 2.0;
  22454. var halfHeight = engine.getRenderHeight() / 2.0;
  22455. if (scene.useRightHandedSystem) {
  22456. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22457. }
  22458. else {
  22459. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22460. }
  22461. this._cache.orthoLeft = this.orthoLeft;
  22462. this._cache.orthoRight = this.orthoRight;
  22463. this._cache.orthoBottom = this.orthoBottom;
  22464. this._cache.orthoTop = this.orthoTop;
  22465. this._cache.renderWidth = engine.getRenderWidth();
  22466. this._cache.renderHeight = engine.getRenderHeight();
  22467. }
  22468. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22469. return this._projectionMatrix;
  22470. };
  22471. Camera.prototype.getTranformationMatrix = function () {
  22472. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22473. return this._transformMatrix;
  22474. };
  22475. Camera.prototype.updateFrustumPlanes = function () {
  22476. if (!this._refreshFrustumPlanes) {
  22477. return;
  22478. }
  22479. this.getTranformationMatrix();
  22480. if (!this._frustumPlanes) {
  22481. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22482. }
  22483. else {
  22484. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22485. }
  22486. this._refreshFrustumPlanes = false;
  22487. };
  22488. Camera.prototype.isInFrustum = function (target) {
  22489. this.updateFrustumPlanes();
  22490. return target.isInFrustum(this._frustumPlanes);
  22491. };
  22492. Camera.prototype.isCompletelyInFrustum = function (target) {
  22493. this.updateFrustumPlanes();
  22494. return target.isCompletelyInFrustum(this._frustumPlanes);
  22495. };
  22496. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22497. if (length === void 0) { length = 100; }
  22498. if (!transform) {
  22499. transform = this.getWorldMatrix();
  22500. }
  22501. if (!origin) {
  22502. origin = this.position;
  22503. }
  22504. var forward = new BABYLON.Vector3(0, 0, 1);
  22505. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22506. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22507. return new BABYLON.Ray(origin, direction, length);
  22508. };
  22509. /**
  22510. * Releases resources associated with this node.
  22511. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22512. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22513. */
  22514. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22515. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22516. // Observables
  22517. this.onViewMatrixChangedObservable.clear();
  22518. this.onProjectionMatrixChangedObservable.clear();
  22519. this.onAfterCheckInputsObservable.clear();
  22520. this.onRestoreStateObservable.clear();
  22521. // Inputs
  22522. if (this.inputs) {
  22523. this.inputs.clear();
  22524. }
  22525. // Animations
  22526. this.getScene().stopAnimation(this);
  22527. // Remove from scene
  22528. this.getScene().removeCamera(this);
  22529. while (this._rigCameras.length > 0) {
  22530. var camera = this._rigCameras.pop();
  22531. if (camera) {
  22532. camera.dispose();
  22533. }
  22534. }
  22535. // Postprocesses
  22536. if (this._rigPostProcess) {
  22537. this._rigPostProcess.dispose(this);
  22538. this._rigPostProcess = null;
  22539. this._postProcesses = [];
  22540. }
  22541. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22542. this._rigPostProcess = null;
  22543. this._postProcesses = [];
  22544. }
  22545. else {
  22546. var i = this._postProcesses.length;
  22547. while (--i >= 0) {
  22548. var postProcess = this._postProcesses[i];
  22549. if (postProcess) {
  22550. postProcess.dispose(this);
  22551. }
  22552. }
  22553. }
  22554. // Render targets
  22555. var i = this.customRenderTargets.length;
  22556. while (--i >= 0) {
  22557. this.customRenderTargets[i].dispose();
  22558. }
  22559. this.customRenderTargets = [];
  22560. // Active Meshes
  22561. this._activeMeshes.dispose();
  22562. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22563. };
  22564. Object.defineProperty(Camera.prototype, "leftCamera", {
  22565. // ---- Camera rigs section ----
  22566. get: function () {
  22567. if (this._rigCameras.length < 1) {
  22568. return null;
  22569. }
  22570. return this._rigCameras[0];
  22571. },
  22572. enumerable: true,
  22573. configurable: true
  22574. });
  22575. Object.defineProperty(Camera.prototype, "rightCamera", {
  22576. get: function () {
  22577. if (this._rigCameras.length < 2) {
  22578. return null;
  22579. }
  22580. return this._rigCameras[1];
  22581. },
  22582. enumerable: true,
  22583. configurable: true
  22584. });
  22585. Camera.prototype.getLeftTarget = function () {
  22586. if (this._rigCameras.length < 1) {
  22587. return null;
  22588. }
  22589. return this._rigCameras[0].getTarget();
  22590. };
  22591. Camera.prototype.getRightTarget = function () {
  22592. if (this._rigCameras.length < 2) {
  22593. return null;
  22594. }
  22595. return this._rigCameras[1].getTarget();
  22596. };
  22597. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22598. if (this.cameraRigMode === mode) {
  22599. return;
  22600. }
  22601. while (this._rigCameras.length > 0) {
  22602. var camera = this._rigCameras.pop();
  22603. if (camera) {
  22604. camera.dispose();
  22605. }
  22606. }
  22607. this.cameraRigMode = mode;
  22608. this._cameraRigParams = {};
  22609. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22610. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22611. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22612. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22613. // create the rig cameras, unless none
  22614. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22615. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22616. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22617. if (leftCamera && rightCamera) {
  22618. this._rigCameras.push(leftCamera);
  22619. this._rigCameras.push(rightCamera);
  22620. }
  22621. }
  22622. switch (this.cameraRigMode) {
  22623. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22624. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22625. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22626. break;
  22627. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22628. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22629. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22630. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22631. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22632. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22633. break;
  22634. case Camera.RIG_MODE_VR:
  22635. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22636. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22637. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22638. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22639. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22640. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22641. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22642. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22643. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22644. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22645. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22646. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22647. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22648. if (metrics.compensateDistortion) {
  22649. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22650. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22651. }
  22652. break;
  22653. case Camera.RIG_MODE_WEBVR:
  22654. if (rigParams.vrDisplay) {
  22655. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22656. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22657. //Left eye
  22658. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22659. this._rigCameras[0].setCameraRigParameter("left", true);
  22660. //leaving this for future reference
  22661. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22662. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22663. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22664. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22665. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22666. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22667. this._rigCameras[0].parent = this;
  22668. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22669. //Right eye
  22670. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22671. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22672. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22673. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22674. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22675. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22676. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22677. this._rigCameras[1].parent = this;
  22678. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22679. if (Camera.UseAlternateWebVRRendering) {
  22680. this._rigCameras[1]._skipRendering = true;
  22681. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22682. }
  22683. }
  22684. break;
  22685. }
  22686. this._cascadePostProcessesToRigCams();
  22687. this.update();
  22688. };
  22689. Camera.prototype._getVRProjectionMatrix = function () {
  22690. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22691. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22692. return this._projectionMatrix;
  22693. };
  22694. Camera.prototype._updateCameraRotationMatrix = function () {
  22695. //Here for WebVR
  22696. };
  22697. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22698. //Here for WebVR
  22699. };
  22700. /**
  22701. * This function MUST be overwritten by the different WebVR cameras available.
  22702. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22703. */
  22704. Camera.prototype._getWebVRProjectionMatrix = function () {
  22705. return BABYLON.Matrix.Identity();
  22706. };
  22707. /**
  22708. * This function MUST be overwritten by the different WebVR cameras available.
  22709. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22710. */
  22711. Camera.prototype._getWebVRViewMatrix = function () {
  22712. return BABYLON.Matrix.Identity();
  22713. };
  22714. Camera.prototype.setCameraRigParameter = function (name, value) {
  22715. if (!this._cameraRigParams) {
  22716. this._cameraRigParams = {};
  22717. }
  22718. this._cameraRigParams[name] = value;
  22719. //provisionnally:
  22720. if (name === "interaxialDistance") {
  22721. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22722. }
  22723. };
  22724. /**
  22725. * needs to be overridden by children so sub has required properties to be copied
  22726. */
  22727. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22728. return null;
  22729. };
  22730. /**
  22731. * May need to be overridden by children
  22732. */
  22733. Camera.prototype._updateRigCameras = function () {
  22734. for (var i = 0; i < this._rigCameras.length; i++) {
  22735. this._rigCameras[i].minZ = this.minZ;
  22736. this._rigCameras[i].maxZ = this.maxZ;
  22737. this._rigCameras[i].fov = this.fov;
  22738. }
  22739. // only update viewport when ANAGLYPH
  22740. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22741. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22742. }
  22743. };
  22744. Camera.prototype._setupInputs = function () {
  22745. };
  22746. Camera.prototype.serialize = function () {
  22747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22748. // Type
  22749. serializationObject.type = this.getClassName();
  22750. // Parent
  22751. if (this.parent) {
  22752. serializationObject.parentId = this.parent.id;
  22753. }
  22754. if (this.inputs) {
  22755. this.inputs.serialize(serializationObject);
  22756. }
  22757. // Animations
  22758. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22759. serializationObject.ranges = this.serializeAnimationRanges();
  22760. return serializationObject;
  22761. };
  22762. Camera.prototype.clone = function (name) {
  22763. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22764. };
  22765. Camera.prototype.getDirection = function (localAxis) {
  22766. var result = BABYLON.Vector3.Zero();
  22767. this.getDirectionToRef(localAxis, result);
  22768. return result;
  22769. };
  22770. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22771. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22772. };
  22773. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22774. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22775. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22776. switch (type) {
  22777. case "ArcRotateCamera":
  22778. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22779. case "DeviceOrientationCamera":
  22780. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22781. case "FollowCamera":
  22782. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22783. case "ArcFollowCamera":
  22784. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22785. case "GamepadCamera":
  22786. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22787. case "TouchCamera":
  22788. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22789. case "VirtualJoysticksCamera":
  22790. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22791. case "WebVRFreeCamera":
  22792. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22793. case "WebVRGamepadCamera":
  22794. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22795. case "VRDeviceOrientationFreeCamera":
  22796. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22797. case "VRDeviceOrientationGamepadCamera":
  22798. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22799. case "AnaglyphArcRotateCamera":
  22800. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22801. case "AnaglyphFreeCamera":
  22802. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22803. case "AnaglyphGamepadCamera":
  22804. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22805. case "AnaglyphUniversalCamera":
  22806. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22807. case "StereoscopicArcRotateCamera":
  22808. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22809. case "StereoscopicFreeCamera":
  22810. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22811. case "StereoscopicGamepadCamera":
  22812. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22813. case "StereoscopicUniversalCamera":
  22814. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22815. case "FreeCamera": // Forcing Universal here
  22816. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22817. default: // Universal Camera is the default value
  22818. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22819. }
  22820. };
  22821. Camera.prototype.computeWorldMatrix = function () {
  22822. return this.getWorldMatrix();
  22823. };
  22824. Camera.Parse = function (parsedCamera, scene) {
  22825. var type = parsedCamera.type;
  22826. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22827. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22828. // Parent
  22829. if (parsedCamera.parentId) {
  22830. camera._waitingParentId = parsedCamera.parentId;
  22831. }
  22832. //If camera has an input manager, let it parse inputs settings
  22833. if (camera.inputs) {
  22834. camera.inputs.parse(parsedCamera);
  22835. camera._setupInputs();
  22836. }
  22837. if (camera.setPosition) { // need to force position
  22838. camera.position.copyFromFloats(0, 0, 0);
  22839. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22840. }
  22841. // Target
  22842. if (parsedCamera.target) {
  22843. if (camera.setTarget) {
  22844. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22845. }
  22846. }
  22847. // Apply 3d rig, when found
  22848. if (parsedCamera.cameraRigMode) {
  22849. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22850. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22851. }
  22852. // Animations
  22853. if (parsedCamera.animations) {
  22854. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22855. var parsedAnimation = parsedCamera.animations[animationIndex];
  22856. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22857. }
  22858. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22859. }
  22860. if (parsedCamera.autoAnimate) {
  22861. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22862. }
  22863. return camera;
  22864. };
  22865. // Statics
  22866. Camera._PERSPECTIVE_CAMERA = 0;
  22867. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22868. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22869. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22870. Camera._RIG_MODE_NONE = 0;
  22871. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22872. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22873. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22874. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22875. Camera._RIG_MODE_VR = 20;
  22876. Camera._RIG_MODE_WEBVR = 21;
  22877. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22878. Camera.UseAlternateWebVRRendering = false;
  22879. __decorate([
  22880. BABYLON.serializeAsVector3()
  22881. ], Camera.prototype, "position", void 0);
  22882. __decorate([
  22883. BABYLON.serializeAsVector3()
  22884. ], Camera.prototype, "upVector", void 0);
  22885. __decorate([
  22886. BABYLON.serialize()
  22887. ], Camera.prototype, "orthoLeft", void 0);
  22888. __decorate([
  22889. BABYLON.serialize()
  22890. ], Camera.prototype, "orthoRight", void 0);
  22891. __decorate([
  22892. BABYLON.serialize()
  22893. ], Camera.prototype, "orthoBottom", void 0);
  22894. __decorate([
  22895. BABYLON.serialize()
  22896. ], Camera.prototype, "orthoTop", void 0);
  22897. __decorate([
  22898. BABYLON.serialize()
  22899. ], Camera.prototype, "fov", void 0);
  22900. __decorate([
  22901. BABYLON.serialize()
  22902. ], Camera.prototype, "minZ", void 0);
  22903. __decorate([
  22904. BABYLON.serialize()
  22905. ], Camera.prototype, "maxZ", void 0);
  22906. __decorate([
  22907. BABYLON.serialize()
  22908. ], Camera.prototype, "inertia", void 0);
  22909. __decorate([
  22910. BABYLON.serialize()
  22911. ], Camera.prototype, "mode", void 0);
  22912. __decorate([
  22913. BABYLON.serialize()
  22914. ], Camera.prototype, "layerMask", void 0);
  22915. __decorate([
  22916. BABYLON.serialize()
  22917. ], Camera.prototype, "fovMode", void 0);
  22918. __decorate([
  22919. BABYLON.serialize()
  22920. ], Camera.prototype, "cameraRigMode", void 0);
  22921. __decorate([
  22922. BABYLON.serialize()
  22923. ], Camera.prototype, "interaxialDistance", void 0);
  22924. __decorate([
  22925. BABYLON.serialize()
  22926. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22927. return Camera;
  22928. }(BABYLON.Node));
  22929. BABYLON.Camera = Camera;
  22930. })(BABYLON || (BABYLON = {}));
  22931. //# sourceMappingURL=babylon.camera.js.map
  22932. var BABYLON;
  22933. (function (BABYLON) {
  22934. var RenderingManager = /** @class */ (function () {
  22935. function RenderingManager(scene) {
  22936. this._renderingGroups = new Array();
  22937. this._autoClearDepthStencil = {};
  22938. this._customOpaqueSortCompareFn = {};
  22939. this._customAlphaTestSortCompareFn = {};
  22940. this._customTransparentSortCompareFn = {};
  22941. this._renderinGroupInfo = null;
  22942. this._scene = scene;
  22943. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22944. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22945. }
  22946. }
  22947. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22948. if (depth === void 0) { depth = true; }
  22949. if (stencil === void 0) { stencil = true; }
  22950. if (this._depthStencilBufferAlreadyCleaned) {
  22951. return;
  22952. }
  22953. this._scene.getEngine().clear(null, false, depth, stencil);
  22954. this._depthStencilBufferAlreadyCleaned = true;
  22955. };
  22956. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22957. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22958. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22959. var info = null;
  22960. if (observable) {
  22961. if (!this._renderinGroupInfo) {
  22962. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22963. }
  22964. info = this._renderinGroupInfo;
  22965. info.scene = this._scene;
  22966. info.camera = this._scene.activeCamera;
  22967. }
  22968. // Dispatch sprites
  22969. if (renderSprites) {
  22970. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22971. var manager = this._scene.spriteManagers[index];
  22972. this.dispatchSprites(manager);
  22973. }
  22974. }
  22975. // Render
  22976. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22977. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22978. var renderingGroup = this._renderingGroups[index];
  22979. if (!renderingGroup && !observable)
  22980. continue;
  22981. var renderingGroupMask = 0;
  22982. // Fire PRECLEAR stage
  22983. if (observable && info) {
  22984. renderingGroupMask = Math.pow(2, index);
  22985. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22986. info.renderingGroupId = index;
  22987. observable.notifyObservers(info, renderingGroupMask);
  22988. }
  22989. // Clear depth/stencil if needed
  22990. if (RenderingManager.AUTOCLEAR) {
  22991. var autoClear = this._autoClearDepthStencil[index];
  22992. if (autoClear && autoClear.autoClear) {
  22993. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22994. }
  22995. }
  22996. if (observable && info) {
  22997. // Fire PREOPAQUE stage
  22998. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22999. observable.notifyObservers(info, renderingGroupMask);
  23000. // Fire PRETRANSPARENT stage
  23001. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23002. observable.notifyObservers(info, renderingGroupMask);
  23003. }
  23004. if (renderingGroup)
  23005. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23006. // Fire POSTTRANSPARENT stage
  23007. if (observable && info) {
  23008. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23009. observable.notifyObservers(info, renderingGroupMask);
  23010. }
  23011. }
  23012. };
  23013. RenderingManager.prototype.reset = function () {
  23014. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23015. var renderingGroup = this._renderingGroups[index];
  23016. if (renderingGroup) {
  23017. renderingGroup.prepare();
  23018. }
  23019. }
  23020. };
  23021. RenderingManager.prototype.dispose = function () {
  23022. this.freeRenderingGroups();
  23023. this._renderingGroups.length = 0;
  23024. };
  23025. /**
  23026. * Clear the info related to rendering groups preventing retention points during dispose.
  23027. */
  23028. RenderingManager.prototype.freeRenderingGroups = function () {
  23029. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23030. var renderingGroup = this._renderingGroups[index];
  23031. if (renderingGroup) {
  23032. renderingGroup.dispose();
  23033. }
  23034. }
  23035. };
  23036. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23037. if (this._renderingGroups[renderingGroupId] === undefined) {
  23038. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23039. }
  23040. };
  23041. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23042. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23043. this._prepareRenderingGroup(renderingGroupId);
  23044. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23045. };
  23046. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23047. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23048. this._prepareRenderingGroup(renderingGroupId);
  23049. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23050. };
  23051. /**
  23052. * @param subMesh The submesh to dispatch
  23053. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23054. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23055. */
  23056. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23057. if (mesh === undefined) {
  23058. mesh = subMesh.getMesh();
  23059. }
  23060. var renderingGroupId = mesh.renderingGroupId || 0;
  23061. this._prepareRenderingGroup(renderingGroupId);
  23062. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23063. };
  23064. /**
  23065. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23066. * This allowed control for front to back rendering or reversly depending of the special needs.
  23067. *
  23068. * @param renderingGroupId The rendering group id corresponding to its index
  23069. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23070. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23071. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23072. */
  23073. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23074. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23075. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23076. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23077. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23078. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23079. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23080. if (this._renderingGroups[renderingGroupId]) {
  23081. var group = this._renderingGroups[renderingGroupId];
  23082. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23083. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23084. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23085. }
  23086. };
  23087. /**
  23088. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23089. *
  23090. * @param renderingGroupId The rendering group id corresponding to its index
  23091. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23092. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23093. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23094. */
  23095. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23096. if (depth === void 0) { depth = true; }
  23097. if (stencil === void 0) { stencil = true; }
  23098. this._autoClearDepthStencil[renderingGroupId] = {
  23099. autoClear: autoClearDepthStencil,
  23100. depth: depth,
  23101. stencil: stencil
  23102. };
  23103. };
  23104. /**
  23105. * The max id used for rendering groups (not included)
  23106. */
  23107. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23108. /**
  23109. * The min id used for rendering groups (included)
  23110. */
  23111. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23112. /**
  23113. * Used to globally prevent autoclearing scenes.
  23114. */
  23115. RenderingManager.AUTOCLEAR = true;
  23116. return RenderingManager;
  23117. }());
  23118. BABYLON.RenderingManager = RenderingManager;
  23119. })(BABYLON || (BABYLON = {}));
  23120. //# sourceMappingURL=babylon.renderingManager.js.map
  23121. var BABYLON;
  23122. (function (BABYLON) {
  23123. var RenderingGroup = /** @class */ (function () {
  23124. /**
  23125. * Creates a new rendering group.
  23126. * @param index The rendering group index
  23127. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23128. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23129. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23130. */
  23131. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23132. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23133. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23134. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23135. this.index = index;
  23136. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23137. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23138. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23139. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23140. this._particleSystems = new BABYLON.SmartArray(256);
  23141. this._spriteManagers = new BABYLON.SmartArray(256);
  23142. this._edgesRenderers = new BABYLON.SmartArray(16);
  23143. this._scene = scene;
  23144. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23145. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23146. this.transparentSortCompareFn = transparentSortCompareFn;
  23147. }
  23148. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23149. /**
  23150. * Set the opaque sort comparison function.
  23151. * If null the sub meshes will be render in the order they were created
  23152. */
  23153. set: function (value) {
  23154. this._opaqueSortCompareFn = value;
  23155. if (value) {
  23156. this._renderOpaque = this.renderOpaqueSorted;
  23157. }
  23158. else {
  23159. this._renderOpaque = RenderingGroup.renderUnsorted;
  23160. }
  23161. },
  23162. enumerable: true,
  23163. configurable: true
  23164. });
  23165. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23166. /**
  23167. * Set the alpha test sort comparison function.
  23168. * If null the sub meshes will be render in the order they were created
  23169. */
  23170. set: function (value) {
  23171. this._alphaTestSortCompareFn = value;
  23172. if (value) {
  23173. this._renderAlphaTest = this.renderAlphaTestSorted;
  23174. }
  23175. else {
  23176. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23177. }
  23178. },
  23179. enumerable: true,
  23180. configurable: true
  23181. });
  23182. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23183. /**
  23184. * Set the transparent sort comparison function.
  23185. * If null the sub meshes will be render in the order they were created
  23186. */
  23187. set: function (value) {
  23188. if (value) {
  23189. this._transparentSortCompareFn = value;
  23190. }
  23191. else {
  23192. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23193. }
  23194. this._renderTransparent = this.renderTransparentSorted;
  23195. },
  23196. enumerable: true,
  23197. configurable: true
  23198. });
  23199. /**
  23200. * Render all the sub meshes contained in the group.
  23201. * @param customRenderFunction Used to override the default render behaviour of the group.
  23202. * @returns true if rendered some submeshes.
  23203. */
  23204. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23205. if (customRenderFunction) {
  23206. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23207. return;
  23208. }
  23209. var engine = this._scene.getEngine();
  23210. // Depth only
  23211. if (this._depthOnlySubMeshes.length !== 0) {
  23212. engine.setColorWrite(false);
  23213. this._renderAlphaTest(this._depthOnlySubMeshes);
  23214. engine.setColorWrite(true);
  23215. }
  23216. // Opaque
  23217. if (this._opaqueSubMeshes.length !== 0) {
  23218. this._renderOpaque(this._opaqueSubMeshes);
  23219. }
  23220. // Alpha test
  23221. if (this._alphaTestSubMeshes.length !== 0) {
  23222. this._renderAlphaTest(this._alphaTestSubMeshes);
  23223. }
  23224. var stencilState = engine.getStencilBuffer();
  23225. engine.setStencilBuffer(false);
  23226. // Sprites
  23227. if (renderSprites) {
  23228. this._renderSprites();
  23229. }
  23230. // Particles
  23231. if (renderParticles) {
  23232. this._renderParticles(activeMeshes);
  23233. }
  23234. if (this.onBeforeTransparentRendering) {
  23235. this.onBeforeTransparentRendering();
  23236. }
  23237. // Transparent
  23238. if (this._transparentSubMeshes.length !== 0) {
  23239. this._renderTransparent(this._transparentSubMeshes);
  23240. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23241. }
  23242. // Set back stencil to false in case it changes before the edge renderer.
  23243. engine.setStencilBuffer(false);
  23244. // Edges
  23245. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23246. this._edgesRenderers.data[edgesRendererIndex].render();
  23247. }
  23248. // Restore Stencil state.
  23249. engine.setStencilBuffer(stencilState);
  23250. };
  23251. /**
  23252. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23253. * @param subMeshes The submeshes to render
  23254. */
  23255. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23256. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23257. };
  23258. /**
  23259. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23260. * @param subMeshes The submeshes to render
  23261. */
  23262. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23263. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23264. };
  23265. /**
  23266. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23267. * @param subMeshes The submeshes to render
  23268. */
  23269. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23270. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23271. };
  23272. /**
  23273. * Renders the submeshes in a specified order.
  23274. * @param subMeshes The submeshes to sort before render
  23275. * @param sortCompareFn The comparison function use to sort
  23276. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23277. * @param transparent Specifies to activate blending if true
  23278. */
  23279. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23280. var subIndex = 0;
  23281. var subMesh;
  23282. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23283. for (; subIndex < subMeshes.length; subIndex++) {
  23284. subMesh = subMeshes.data[subIndex];
  23285. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23286. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23287. }
  23288. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23289. if (sortCompareFn) {
  23290. sortedArray.sort(sortCompareFn);
  23291. }
  23292. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23293. subMesh = sortedArray[subIndex];
  23294. if (transparent) {
  23295. var material = subMesh.getMaterial();
  23296. if (material && material.needDepthPrePass) {
  23297. var engine = material.getScene().getEngine();
  23298. engine.setColorWrite(false);
  23299. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23300. subMesh.render(false);
  23301. engine.setColorWrite(true);
  23302. }
  23303. }
  23304. subMesh.render(transparent);
  23305. }
  23306. };
  23307. /**
  23308. * Renders the submeshes in the order they were dispatched (no sort applied).
  23309. * @param subMeshes The submeshes to render
  23310. */
  23311. RenderingGroup.renderUnsorted = function (subMeshes) {
  23312. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23313. var submesh = subMeshes.data[subIndex];
  23314. submesh.render(false);
  23315. }
  23316. };
  23317. /**
  23318. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23319. * are rendered back to front if in the same alpha index.
  23320. *
  23321. * @param a The first submesh
  23322. * @param b The second submesh
  23323. * @returns The result of the comparison
  23324. */
  23325. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23326. // Alpha index first
  23327. if (a._alphaIndex > b._alphaIndex) {
  23328. return 1;
  23329. }
  23330. if (a._alphaIndex < b._alphaIndex) {
  23331. return -1;
  23332. }
  23333. // Then distance to camera
  23334. return RenderingGroup.backToFrontSortCompare(a, b);
  23335. };
  23336. /**
  23337. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23338. * are rendered back to front.
  23339. *
  23340. * @param a The first submesh
  23341. * @param b The second submesh
  23342. * @returns The result of the comparison
  23343. */
  23344. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23345. // Then distance to camera
  23346. if (a._distanceToCamera < b._distanceToCamera) {
  23347. return 1;
  23348. }
  23349. if (a._distanceToCamera > b._distanceToCamera) {
  23350. return -1;
  23351. }
  23352. return 0;
  23353. };
  23354. /**
  23355. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23356. * are rendered front to back (prevent overdraw).
  23357. *
  23358. * @param a The first submesh
  23359. * @param b The second submesh
  23360. * @returns The result of the comparison
  23361. */
  23362. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23363. // Then distance to camera
  23364. if (a._distanceToCamera < b._distanceToCamera) {
  23365. return -1;
  23366. }
  23367. if (a._distanceToCamera > b._distanceToCamera) {
  23368. return 1;
  23369. }
  23370. return 0;
  23371. };
  23372. /**
  23373. * Resets the different lists of submeshes to prepare a new frame.
  23374. */
  23375. RenderingGroup.prototype.prepare = function () {
  23376. this._opaqueSubMeshes.reset();
  23377. this._transparentSubMeshes.reset();
  23378. this._alphaTestSubMeshes.reset();
  23379. this._depthOnlySubMeshes.reset();
  23380. this._particleSystems.reset();
  23381. this._spriteManagers.reset();
  23382. this._edgesRenderers.reset();
  23383. };
  23384. RenderingGroup.prototype.dispose = function () {
  23385. this._opaqueSubMeshes.dispose();
  23386. this._transparentSubMeshes.dispose();
  23387. this._alphaTestSubMeshes.dispose();
  23388. this._depthOnlySubMeshes.dispose();
  23389. this._particleSystems.dispose();
  23390. this._spriteManagers.dispose();
  23391. this._edgesRenderers.dispose();
  23392. };
  23393. /**
  23394. * Inserts the submesh in its correct queue depending on its material.
  23395. * @param subMesh The submesh to dispatch
  23396. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23397. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23398. */
  23399. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23400. // Get mesh and materials if not provided
  23401. if (mesh === undefined) {
  23402. mesh = subMesh.getMesh();
  23403. }
  23404. if (material === undefined) {
  23405. material = subMesh.getMaterial();
  23406. }
  23407. if (material === null || material === undefined) {
  23408. return;
  23409. }
  23410. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23411. this._transparentSubMeshes.push(subMesh);
  23412. }
  23413. else if (material.needAlphaTesting()) { // Alpha test
  23414. if (material.needDepthPrePass) {
  23415. this._depthOnlySubMeshes.push(subMesh);
  23416. }
  23417. this._alphaTestSubMeshes.push(subMesh);
  23418. }
  23419. else {
  23420. if (material.needDepthPrePass) {
  23421. this._depthOnlySubMeshes.push(subMesh);
  23422. }
  23423. this._opaqueSubMeshes.push(subMesh); // Opaque
  23424. }
  23425. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23426. this._edgesRenderers.push(mesh._edgesRenderer);
  23427. }
  23428. };
  23429. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23430. this._spriteManagers.push(spriteManager);
  23431. };
  23432. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23433. this._particleSystems.push(particleSystem);
  23434. };
  23435. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23436. if (this._particleSystems.length === 0) {
  23437. return;
  23438. }
  23439. // Particles
  23440. var activeCamera = this._scene.activeCamera;
  23441. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23442. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23443. var particleSystem = this._particleSystems.data[particleIndex];
  23444. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23445. continue;
  23446. }
  23447. var emitter = particleSystem.emitter;
  23448. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23449. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23450. }
  23451. }
  23452. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23453. };
  23454. RenderingGroup.prototype._renderSprites = function () {
  23455. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23456. return;
  23457. }
  23458. // Sprites
  23459. var activeCamera = this._scene.activeCamera;
  23460. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23461. for (var id = 0; id < this._spriteManagers.length; id++) {
  23462. var spriteManager = this._spriteManagers.data[id];
  23463. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23464. spriteManager.render();
  23465. }
  23466. }
  23467. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23468. };
  23469. return RenderingGroup;
  23470. }());
  23471. BABYLON.RenderingGroup = RenderingGroup;
  23472. })(BABYLON || (BABYLON = {}));
  23473. //# sourceMappingURL=babylon.renderingGroup.js.map
  23474. var BABYLON;
  23475. (function (BABYLON) {
  23476. /** @hidden */
  23477. var ClickInfo = /** @class */ (function () {
  23478. function ClickInfo() {
  23479. this._singleClick = false;
  23480. this._doubleClick = false;
  23481. this._hasSwiped = false;
  23482. this._ignore = false;
  23483. }
  23484. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23485. get: function () {
  23486. return this._singleClick;
  23487. },
  23488. set: function (b) {
  23489. this._singleClick = b;
  23490. },
  23491. enumerable: true,
  23492. configurable: true
  23493. });
  23494. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23495. get: function () {
  23496. return this._doubleClick;
  23497. },
  23498. set: function (b) {
  23499. this._doubleClick = b;
  23500. },
  23501. enumerable: true,
  23502. configurable: true
  23503. });
  23504. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23505. get: function () {
  23506. return this._hasSwiped;
  23507. },
  23508. set: function (b) {
  23509. this._hasSwiped = b;
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23515. get: function () {
  23516. return this._ignore;
  23517. },
  23518. set: function (b) {
  23519. this._ignore = b;
  23520. },
  23521. enumerable: true,
  23522. configurable: true
  23523. });
  23524. return ClickInfo;
  23525. }());
  23526. /**
  23527. * This class is used by the onRenderingGroupObservable
  23528. */
  23529. var RenderingGroupInfo = /** @class */ (function () {
  23530. function RenderingGroupInfo() {
  23531. }
  23532. /**
  23533. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23534. * This stage will be fired no matter what
  23535. */
  23536. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23537. /**
  23538. * Called before opaque object are rendered.
  23539. * This stage will be fired only if there's 3D Opaque content to render
  23540. */
  23541. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23542. /**
  23543. * Called after the opaque objects are rendered and before the transparent ones
  23544. * This stage will be fired only if there's 3D transparent content to render
  23545. */
  23546. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23547. /**
  23548. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23549. * This stage will be fired no matter what
  23550. */
  23551. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23552. return RenderingGroupInfo;
  23553. }());
  23554. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23555. /**
  23556. * Represents a scene to be rendered by the engine.
  23557. * @see http://doc.babylonjs.com/features/scene
  23558. */
  23559. var Scene = /** @class */ (function () {
  23560. /**
  23561. * Creates a new Scene
  23562. * @param engine defines the engine to use to render this scene
  23563. */
  23564. function Scene(engine) {
  23565. // Members
  23566. /**
  23567. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23568. */
  23569. this.autoClear = true;
  23570. /**
  23571. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23572. */
  23573. this.autoClearDepthAndStencil = true;
  23574. /**
  23575. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23576. */
  23577. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23578. /**
  23579. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23580. */
  23581. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23582. this._forceWireframe = false;
  23583. this._forcePointsCloud = false;
  23584. /**
  23585. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23586. */
  23587. this.forceShowBoundingBoxes = false;
  23588. /**
  23589. * Gets or sets a boolean indicating if animations are enabled
  23590. */
  23591. this.animationsEnabled = true;
  23592. this._animationPropertiesOverride = null;
  23593. /**
  23594. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23595. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23596. */
  23597. this.useConstantAnimationDeltaTime = false;
  23598. /**
  23599. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23600. * Please note that it requires to run a ray cast through the scene on every frame
  23601. */
  23602. this.constantlyUpdateMeshUnderPointer = false;
  23603. /**
  23604. * Defines the HTML cursor to use when hovering over interactive elements
  23605. */
  23606. this.hoverCursor = "pointer";
  23607. /**
  23608. * Defines the HTML default cursor to use (empty by default)
  23609. */
  23610. this.defaultCursor = "";
  23611. /**
  23612. * This is used to call preventDefault() on pointer down
  23613. * in order to block unwanted artifacts like system double clicks
  23614. */
  23615. this.preventDefaultOnPointerDown = true;
  23616. // Metadata
  23617. /**
  23618. * Gets or sets user defined metadata
  23619. */
  23620. this.metadata = null;
  23621. /**
  23622. * Use this array to add regular expressions used to disable offline support for specific urls
  23623. */
  23624. this.disableOfflineSupportExceptionRules = new Array();
  23625. /**
  23626. * An event triggered when the scene is disposed.
  23627. */
  23628. this.onDisposeObservable = new BABYLON.Observable();
  23629. this._onDisposeObserver = null;
  23630. /**
  23631. * An event triggered before rendering the scene (right after animations and physics)
  23632. */
  23633. this.onBeforeRenderObservable = new BABYLON.Observable();
  23634. this._onBeforeRenderObserver = null;
  23635. /**
  23636. * An event triggered after rendering the scene
  23637. */
  23638. this.onAfterRenderObservable = new BABYLON.Observable();
  23639. this._onAfterRenderObserver = null;
  23640. /**
  23641. * An event triggered before animating the scene
  23642. */
  23643. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23644. /**
  23645. * An event triggered after animations processing
  23646. */
  23647. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23648. /**
  23649. * An event triggered before draw calls are ready to be sent
  23650. */
  23651. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered after draw calls have been sent
  23654. */
  23655. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23656. /**
  23657. * An event triggered when physic simulation is about to be run
  23658. */
  23659. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23660. /**
  23661. * An event triggered when physic simulation has been done
  23662. */
  23663. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23664. /**
  23665. * An event triggered when the scene is ready
  23666. */
  23667. this.onReadyObservable = new BABYLON.Observable();
  23668. /**
  23669. * An event triggered before rendering a camera
  23670. */
  23671. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23672. this._onBeforeCameraRenderObserver = null;
  23673. /**
  23674. * An event triggered after rendering a camera
  23675. */
  23676. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23677. this._onAfterCameraRenderObserver = null;
  23678. /**
  23679. * An event triggered when active meshes evaluation is about to start
  23680. */
  23681. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23682. /**
  23683. * An event triggered when active meshes evaluation is done
  23684. */
  23685. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23686. /**
  23687. * An event triggered when particles rendering is about to start
  23688. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23689. */
  23690. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered when particles rendering is done
  23693. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23694. */
  23695. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23696. /**
  23697. * An event triggered when sprites rendering is about to start
  23698. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23699. */
  23700. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23701. /**
  23702. * An event triggered when sprites rendering is done
  23703. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23704. */
  23705. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23706. /**
  23707. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23708. */
  23709. this.onDataLoadedObservable = new BABYLON.Observable();
  23710. /**
  23711. * An event triggered when a camera is created
  23712. */
  23713. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered when a camera is removed
  23716. */
  23717. this.onCameraRemovedObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered when a light is created
  23720. */
  23721. this.onNewLightAddedObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered when a light is removed
  23724. */
  23725. this.onLightRemovedObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered when a geometry is created
  23728. */
  23729. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when a geometry is removed
  23732. */
  23733. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when a transform node is created
  23736. */
  23737. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered when a transform node is removed
  23740. */
  23741. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23742. /**
  23743. * An event triggered when a mesh is created
  23744. */
  23745. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23746. /**
  23747. * An event triggered when a mesh is removed
  23748. */
  23749. this.onMeshRemovedObservable = new BABYLON.Observable();
  23750. /**
  23751. * An event triggered when render targets are about to be rendered
  23752. * Can happen multiple times per frame.
  23753. */
  23754. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23755. /**
  23756. * An event triggered when render targets were rendered.
  23757. * Can happen multiple times per frame.
  23758. */
  23759. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23760. /**
  23761. * An event triggered before calculating deterministic simulation step
  23762. */
  23763. this.onBeforeStepObservable = new BABYLON.Observable();
  23764. /**
  23765. * An event triggered after calculating deterministic simulation step
  23766. */
  23767. this.onAfterStepObservable = new BABYLON.Observable();
  23768. /**
  23769. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23770. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23771. * 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)
  23772. */
  23773. this.onRenderingGroupObservable = new BABYLON.Observable();
  23774. // Animations
  23775. /**
  23776. * Gets a list of Animations associated with the scene
  23777. */
  23778. this.animations = [];
  23779. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23780. /**
  23781. * 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).
  23782. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23783. */
  23784. this.onPrePointerObservable = new BABYLON.Observable();
  23785. /**
  23786. * Observable event triggered each time an input event is received from the rendering canvas
  23787. */
  23788. this.onPointerObservable = new BABYLON.Observable();
  23789. this._meshPickProceed = false;
  23790. this._currentPickResult = null;
  23791. this._previousPickResult = null;
  23792. this._totalPointersPressed = 0;
  23793. this._doubleClickOccured = false;
  23794. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23795. this.cameraToUseForPointers = null;
  23796. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23797. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23798. this._startingPointerTime = 0;
  23799. this._previousStartingPointerTime = 0;
  23800. this._pointerCaptures = {};
  23801. // Deterministic lockstep
  23802. this._timeAccumulator = 0;
  23803. this._currentStepId = 0;
  23804. this._currentInternalStep = 0;
  23805. // Keyboard
  23806. /**
  23807. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23808. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23809. */
  23810. this.onPreKeyboardObservable = new BABYLON.Observable();
  23811. /**
  23812. * Observable event triggered each time an keyboard event is received from the hosting window
  23813. */
  23814. this.onKeyboardObservable = new BABYLON.Observable();
  23815. // Coordinates system
  23816. this._useRightHandedSystem = false;
  23817. // Fog
  23818. this._fogEnabled = true;
  23819. this._fogMode = Scene.FOGMODE_NONE;
  23820. /**
  23821. * Gets or sets the fog color to use
  23822. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23823. */
  23824. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23825. /**
  23826. * Gets or sets the fog density to use
  23827. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23828. */
  23829. this.fogDensity = 0.1;
  23830. /**
  23831. * Gets or sets the fog start distance to use
  23832. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23833. */
  23834. this.fogStart = 0;
  23835. /**
  23836. * Gets or sets the fog end distance to use
  23837. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23838. */
  23839. this.fogEnd = 1000.0;
  23840. // Lights
  23841. this._shadowsEnabled = true;
  23842. this._lightsEnabled = true;
  23843. /**
  23844. * All of the lights added to this scene
  23845. * @see http://doc.babylonjs.com/babylon101/lights
  23846. */
  23847. this.lights = new Array();
  23848. // Cameras
  23849. /** All of the cameras added to this scene.
  23850. * @see http://doc.babylonjs.com/babylon101/cameras
  23851. */
  23852. this.cameras = new Array();
  23853. /** All of the active cameras added to this scene. */
  23854. this.activeCameras = new Array();
  23855. // Meshes
  23856. /**
  23857. * All of the tranform nodes added to this scene
  23858. * @see http://doc.babylonjs.com/how_to/transformnode
  23859. */
  23860. this.transformNodes = new Array();
  23861. /**
  23862. * All of the (abstract) meshes added to this scene
  23863. */
  23864. this.meshes = new Array();
  23865. /**
  23866. * All of the animation groups added to this scene
  23867. * @see http://doc.babylonjs.com/how_to/group
  23868. */
  23869. this.animationGroups = new Array();
  23870. // Geometries
  23871. this._geometries = new Array();
  23872. /**
  23873. * All of the materials added to this scene
  23874. * @see http://doc.babylonjs.com/babylon101/materials
  23875. */
  23876. this.materials = new Array();
  23877. /**
  23878. * All of the multi-materials added to this scene
  23879. * @see http://doc.babylonjs.com/how_to/multi_materials
  23880. */
  23881. this.multiMaterials = new Array();
  23882. // Textures
  23883. this._texturesEnabled = true;
  23884. /**
  23885. * All of the textures added to this scene
  23886. */
  23887. this.textures = new Array();
  23888. // Particles
  23889. /**
  23890. * Gets or sets a boolean indicating if particles are enabled on this scene
  23891. */
  23892. this.particlesEnabled = true;
  23893. /**
  23894. * All of the particle systems added to this scene
  23895. * @see http://doc.babylonjs.com/babylon101/particles
  23896. */
  23897. this.particleSystems = new Array();
  23898. // Sprites
  23899. /**
  23900. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23901. */
  23902. this.spritesEnabled = true;
  23903. /**
  23904. * All of the sprite managers added to this scene
  23905. * @see http://doc.babylonjs.com/babylon101/sprites
  23906. */
  23907. this.spriteManagers = new Array();
  23908. /**
  23909. * The list of layers (background and foreground) of the scene
  23910. */
  23911. this.layers = new Array();
  23912. /**
  23913. * The list of effect layers (highlights/glow) added to the scene
  23914. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23915. * @see http://doc.babylonjs.com/how_to/glow_layer
  23916. */
  23917. this.effectLayers = new Array();
  23918. // Skeletons
  23919. this._skeletonsEnabled = true;
  23920. /**
  23921. * The list of skeletons added to the scene
  23922. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23923. */
  23924. this.skeletons = new Array();
  23925. // Morph targets
  23926. /**
  23927. * The list of morph target managers added to the scene
  23928. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23929. */
  23930. this.morphTargetManagers = new Array();
  23931. // Lens flares
  23932. /**
  23933. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23934. */
  23935. this.lensFlaresEnabled = true;
  23936. /**
  23937. * The list of lens flare system added to the scene
  23938. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23939. */
  23940. this.lensFlareSystems = new Array();
  23941. // Collisions
  23942. /**
  23943. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23944. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23945. */
  23946. this.collisionsEnabled = true;
  23947. /**
  23948. * Defines the gravity applied to this scene (used only for collisions)
  23949. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23950. */
  23951. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23952. // Postprocesses
  23953. /**
  23954. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23955. */
  23956. this.postProcessesEnabled = true;
  23957. /**
  23958. * The list of postprocesses added to the scene
  23959. */
  23960. this.postProcesses = new Array();
  23961. // Customs render targets
  23962. /**
  23963. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23964. */
  23965. this.renderTargetsEnabled = true;
  23966. /**
  23967. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23968. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23969. */
  23970. this.dumpNextRenderTargets = false;
  23971. /**
  23972. * The list of user defined render targets added to the scene
  23973. */
  23974. this.customRenderTargets = new Array();
  23975. /**
  23976. * Gets the list of meshes imported to the scene through SceneLoader
  23977. */
  23978. this.importedMeshesFiles = new Array();
  23979. // Probes
  23980. /**
  23981. * Gets or sets a boolean indicating if probes are enabled on this scene
  23982. */
  23983. this.probesEnabled = true;
  23984. /**
  23985. * The list of reflection probes added to the scene
  23986. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23987. */
  23988. this.reflectionProbes = new Array();
  23989. /** @hidden */
  23990. this._actionManagers = new Array();
  23991. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23992. // Procedural textures
  23993. /**
  23994. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23995. */
  23996. this.proceduralTexturesEnabled = true;
  23997. /**
  23998. * The list of procedural textures added to the scene
  23999. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24000. */
  24001. this.proceduralTextures = new Array();
  24002. /**
  24003. * The list of sound tracks added to the scene
  24004. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24005. */
  24006. this.soundTracks = new Array();
  24007. this._audioEnabled = true;
  24008. this._headphone = false;
  24009. // Performance counters
  24010. this._totalVertices = new BABYLON.PerfCounter();
  24011. /** @hidden */
  24012. this._activeIndices = new BABYLON.PerfCounter();
  24013. /** @hidden */
  24014. this._activeParticles = new BABYLON.PerfCounter();
  24015. /** @hidden */
  24016. this._activeBones = new BABYLON.PerfCounter();
  24017. this._animationTime = 0;
  24018. /**
  24019. * Gets or sets a general scale for animation speed
  24020. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24021. */
  24022. this.animationTimeScale = 1;
  24023. this._renderId = 0;
  24024. this._executeWhenReadyTimeoutId = -1;
  24025. this._intermediateRendering = false;
  24026. this._viewUpdateFlag = -1;
  24027. this._projectionUpdateFlag = -1;
  24028. this._alternateViewUpdateFlag = -1;
  24029. this._alternateProjectionUpdateFlag = -1;
  24030. /** @hidden */
  24031. this._toBeDisposed = new BABYLON.SmartArray(256);
  24032. this._activeRequests = new Array();
  24033. this._pendingData = new Array();
  24034. this._isDisposed = false;
  24035. /**
  24036. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24037. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24038. */
  24039. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24040. this._activeMeshes = new BABYLON.SmartArray(256);
  24041. this._processedMaterials = new BABYLON.SmartArray(256);
  24042. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24043. /** @hidden */
  24044. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24045. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24046. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24047. /** @hidden */
  24048. this._activeAnimatables = new Array();
  24049. this._transformMatrix = BABYLON.Matrix.Zero();
  24050. this._useAlternateCameraConfiguration = false;
  24051. this._alternateRendering = false;
  24052. /**
  24053. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24054. * This is useful if there are more lights that the maximum simulteanous authorized
  24055. */
  24056. this.requireLightSorting = false;
  24057. this._depthRenderer = {};
  24058. this._activeMeshesFrozen = false;
  24059. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24060. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24061. this._engine.scenes.push(this);
  24062. this._uid = null;
  24063. this._renderingManager = new BABYLON.RenderingManager(this);
  24064. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24065. if (BABYLON.OutlineRenderer) {
  24066. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24067. }
  24068. if (BABYLON.Tools.IsWindowObjectExist()) {
  24069. this.attachControl();
  24070. }
  24071. //simplification queue
  24072. if (BABYLON.SimplificationQueue) {
  24073. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24074. }
  24075. //collision coordinator initialization. For now legacy per default.
  24076. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24077. // Uniform Buffer
  24078. this._createUbo();
  24079. // Default Image processing definition.
  24080. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24081. }
  24082. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24083. /** The fog is deactivated */
  24084. get: function () {
  24085. return Scene._FOGMODE_NONE;
  24086. },
  24087. enumerable: true,
  24088. configurable: true
  24089. });
  24090. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24091. /** The fog density is following an exponential function */
  24092. get: function () {
  24093. return Scene._FOGMODE_EXP;
  24094. },
  24095. enumerable: true,
  24096. configurable: true
  24097. });
  24098. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24099. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24100. get: function () {
  24101. return Scene._FOGMODE_EXP2;
  24102. },
  24103. enumerable: true,
  24104. configurable: true
  24105. });
  24106. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24107. /** The fog density is following a linear function. */
  24108. get: function () {
  24109. return Scene._FOGMODE_LINEAR;
  24110. },
  24111. enumerable: true,
  24112. configurable: true
  24113. });
  24114. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24115. /**
  24116. * Texture used in all pbr material as the reflection texture.
  24117. * As in the majority of the scene they are the same (exception for multi room and so on),
  24118. * this is easier to reference from here than from all the materials.
  24119. */
  24120. get: function () {
  24121. return this._environmentTexture;
  24122. },
  24123. /**
  24124. * Texture used in all pbr material as the reflection texture.
  24125. * As in the majority of the scene they are the same (exception for multi room and so on),
  24126. * this is easier to set here than in all the materials.
  24127. */
  24128. set: function (value) {
  24129. if (this._environmentTexture === value) {
  24130. return;
  24131. }
  24132. this._environmentTexture = value;
  24133. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24139. /**
  24140. * Default image processing configuration used either in the rendering
  24141. * Forward main pass or through the imageProcessingPostProcess if present.
  24142. * As in the majority of the scene they are the same (exception for multi camera),
  24143. * this is easier to reference from here than from all the materials and post process.
  24144. *
  24145. * No setter as we it is a shared configuration, you can set the values instead.
  24146. */
  24147. get: function () {
  24148. return this._imageProcessingConfiguration;
  24149. },
  24150. enumerable: true,
  24151. configurable: true
  24152. });
  24153. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24154. get: function () {
  24155. return this._forceWireframe;
  24156. },
  24157. /**
  24158. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24159. */
  24160. set: function (value) {
  24161. if (this._forceWireframe === value) {
  24162. return;
  24163. }
  24164. this._forceWireframe = value;
  24165. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24166. },
  24167. enumerable: true,
  24168. configurable: true
  24169. });
  24170. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24171. get: function () {
  24172. return this._forcePointsCloud;
  24173. },
  24174. /**
  24175. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24176. */
  24177. set: function (value) {
  24178. if (this._forcePointsCloud === value) {
  24179. return;
  24180. }
  24181. this._forcePointsCloud = value;
  24182. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24188. /**
  24189. * Gets or sets the animation properties override
  24190. */
  24191. get: function () {
  24192. return this._animationPropertiesOverride;
  24193. },
  24194. set: function (value) {
  24195. this._animationPropertiesOverride = value;
  24196. },
  24197. enumerable: true,
  24198. configurable: true
  24199. });
  24200. Object.defineProperty(Scene.prototype, "onDispose", {
  24201. /** Sets a function to be executed when this scene is disposed. */
  24202. set: function (callback) {
  24203. if (this._onDisposeObserver) {
  24204. this.onDisposeObservable.remove(this._onDisposeObserver);
  24205. }
  24206. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. Object.defineProperty(Scene.prototype, "beforeRender", {
  24212. /** Sets a function to be executed before rendering this scene */
  24213. set: function (callback) {
  24214. if (this._onBeforeRenderObserver) {
  24215. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24216. }
  24217. if (callback) {
  24218. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24219. }
  24220. },
  24221. enumerable: true,
  24222. configurable: true
  24223. });
  24224. Object.defineProperty(Scene.prototype, "afterRender", {
  24225. /** Sets a function to be executed after rendering this scene */
  24226. set: function (callback) {
  24227. if (this._onAfterRenderObserver) {
  24228. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24229. }
  24230. if (callback) {
  24231. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24232. }
  24233. },
  24234. enumerable: true,
  24235. configurable: true
  24236. });
  24237. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24238. /** Sets a function to be executed before rendering a camera*/
  24239. set: function (callback) {
  24240. if (this._onBeforeCameraRenderObserver) {
  24241. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24242. }
  24243. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24244. },
  24245. enumerable: true,
  24246. configurable: true
  24247. });
  24248. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24249. /** Sets a function to be executed after rendering a camera*/
  24250. set: function (callback) {
  24251. if (this._onAfterCameraRenderObserver) {
  24252. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24253. }
  24254. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24255. },
  24256. enumerable: true,
  24257. configurable: true
  24258. });
  24259. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24260. /**
  24261. * Gets the gamepad manager associated with the scene
  24262. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24263. */
  24264. get: function () {
  24265. if (!this._gamepadManager) {
  24266. this._gamepadManager = new BABYLON.GamepadManager(this);
  24267. }
  24268. return this._gamepadManager;
  24269. },
  24270. enumerable: true,
  24271. configurable: true
  24272. });
  24273. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24274. /**
  24275. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24276. */
  24277. get: function () {
  24278. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24279. },
  24280. enumerable: true,
  24281. configurable: true
  24282. });
  24283. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24284. get: function () {
  24285. return this._useRightHandedSystem;
  24286. },
  24287. /**
  24288. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24289. */
  24290. set: function (value) {
  24291. if (this._useRightHandedSystem === value) {
  24292. return;
  24293. }
  24294. this._useRightHandedSystem = value;
  24295. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24296. },
  24297. enumerable: true,
  24298. configurable: true
  24299. });
  24300. /**
  24301. * Sets the step Id used by deterministic lock step
  24302. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24303. * @param newStepId defines the step Id
  24304. */
  24305. Scene.prototype.setStepId = function (newStepId) {
  24306. this._currentStepId = newStepId;
  24307. };
  24308. ;
  24309. /**
  24310. * Gets the step Id used by deterministic lock step
  24311. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24312. * @returns the step Id
  24313. */
  24314. Scene.prototype.getStepId = function () {
  24315. return this._currentStepId;
  24316. };
  24317. ;
  24318. /**
  24319. * Gets the internal step used by deterministic lock step
  24320. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24321. * @returns the internal step
  24322. */
  24323. Scene.prototype.getInternalStep = function () {
  24324. return this._currentInternalStep;
  24325. };
  24326. ;
  24327. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24328. get: function () {
  24329. return this._fogEnabled;
  24330. },
  24331. /**
  24332. * Gets or sets a boolean indicating if fog is enabled on this scene
  24333. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24334. */
  24335. set: function (value) {
  24336. if (this._fogEnabled === value) {
  24337. return;
  24338. }
  24339. this._fogEnabled = value;
  24340. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24341. },
  24342. enumerable: true,
  24343. configurable: true
  24344. });
  24345. Object.defineProperty(Scene.prototype, "fogMode", {
  24346. get: function () {
  24347. return this._fogMode;
  24348. },
  24349. /**
  24350. * Gets or sets the fog mode to use
  24351. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24352. */
  24353. set: function (value) {
  24354. if (this._fogMode === value) {
  24355. return;
  24356. }
  24357. this._fogMode = value;
  24358. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24359. },
  24360. enumerable: true,
  24361. configurable: true
  24362. });
  24363. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24364. get: function () {
  24365. return this._shadowsEnabled;
  24366. },
  24367. /**
  24368. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24369. */
  24370. set: function (value) {
  24371. if (this._shadowsEnabled === value) {
  24372. return;
  24373. }
  24374. this._shadowsEnabled = value;
  24375. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24376. },
  24377. enumerable: true,
  24378. configurable: true
  24379. });
  24380. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24381. get: function () {
  24382. return this._lightsEnabled;
  24383. },
  24384. /**
  24385. * Gets or sets a boolean indicating if lights are enabled on this scene
  24386. */
  24387. set: function (value) {
  24388. if (this._lightsEnabled === value) {
  24389. return;
  24390. }
  24391. this._lightsEnabled = value;
  24392. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24393. },
  24394. enumerable: true,
  24395. configurable: true
  24396. });
  24397. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24398. /** The default material used on meshes when no material is affected */
  24399. get: function () {
  24400. if (!this._defaultMaterial) {
  24401. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24402. }
  24403. return this._defaultMaterial;
  24404. },
  24405. /** The default material used on meshes when no material is affected */
  24406. set: function (value) {
  24407. this._defaultMaterial = value;
  24408. },
  24409. enumerable: true,
  24410. configurable: true
  24411. });
  24412. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24413. get: function () {
  24414. return this._texturesEnabled;
  24415. },
  24416. /**
  24417. * Gets or sets a boolean indicating if textures are enabled on this scene
  24418. */
  24419. set: function (value) {
  24420. if (this._texturesEnabled === value) {
  24421. return;
  24422. }
  24423. this._texturesEnabled = value;
  24424. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24425. },
  24426. enumerable: true,
  24427. configurable: true
  24428. });
  24429. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24430. get: function () {
  24431. return this._skeletonsEnabled;
  24432. },
  24433. /**
  24434. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24435. */
  24436. set: function (value) {
  24437. if (this._skeletonsEnabled === value) {
  24438. return;
  24439. }
  24440. this._skeletonsEnabled = value;
  24441. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24442. },
  24443. enumerable: true,
  24444. configurable: true
  24445. });
  24446. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24447. /**
  24448. * Gets the postprocess render pipeline manager
  24449. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24450. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24451. */
  24452. get: function () {
  24453. if (!this._postProcessRenderPipelineManager) {
  24454. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24455. }
  24456. return this._postProcessRenderPipelineManager;
  24457. },
  24458. enumerable: true,
  24459. configurable: true
  24460. });
  24461. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24462. /**
  24463. * Gets the main soundtrack associated with the scene
  24464. */
  24465. get: function () {
  24466. if (!this._mainSoundTrack) {
  24467. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24468. }
  24469. return this._mainSoundTrack;
  24470. },
  24471. enumerable: true,
  24472. configurable: true
  24473. });
  24474. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24475. /** @hidden */
  24476. get: function () {
  24477. return this._alternateRendering;
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24483. /**
  24484. * Gets the list of frustum planes (built from the active camera)
  24485. */
  24486. get: function () {
  24487. return this._frustumPlanes;
  24488. },
  24489. enumerable: true,
  24490. configurable: true
  24491. });
  24492. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24493. /**
  24494. * Gets the current geometry buffer associated to the scene.
  24495. */
  24496. get: function () {
  24497. return this._geometryBufferRenderer;
  24498. },
  24499. /**
  24500. * Sets the current geometry buffer for the scene.
  24501. */
  24502. set: function (geometryBufferRenderer) {
  24503. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24504. this._geometryBufferRenderer = geometryBufferRenderer;
  24505. }
  24506. },
  24507. enumerable: true,
  24508. configurable: true
  24509. });
  24510. Object.defineProperty(Scene.prototype, "debugLayer", {
  24511. /**
  24512. * Gets the debug layer associated with the scene
  24513. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24514. */
  24515. get: function () {
  24516. if (!this._debugLayer) {
  24517. this._debugLayer = new BABYLON.DebugLayer(this);
  24518. }
  24519. return this._debugLayer;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24525. /**
  24526. * Gets a boolean indicating if collisions are processed on a web worker
  24527. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24528. */
  24529. get: function () {
  24530. return this._workerCollisions;
  24531. },
  24532. set: function (enabled) {
  24533. if (!BABYLON.CollisionCoordinatorLegacy) {
  24534. return;
  24535. }
  24536. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24537. this._workerCollisions = enabled;
  24538. if (this.collisionCoordinator) {
  24539. this.collisionCoordinator.destroy();
  24540. }
  24541. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24542. this.collisionCoordinator.init(this);
  24543. },
  24544. enumerable: true,
  24545. configurable: true
  24546. });
  24547. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24548. /**
  24549. * Gets the octree used to boost mesh selection (picking)
  24550. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24551. */
  24552. get: function () {
  24553. return this._selectionOctree;
  24554. },
  24555. enumerable: true,
  24556. configurable: true
  24557. });
  24558. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24559. /**
  24560. * Gets the mesh that is currently under the pointer
  24561. */
  24562. get: function () {
  24563. return this._pointerOverMesh;
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(Scene.prototype, "pointerX", {
  24569. /**
  24570. * Gets the current on-screen X position of the pointer
  24571. */
  24572. get: function () {
  24573. return this._pointerX;
  24574. },
  24575. enumerable: true,
  24576. configurable: true
  24577. });
  24578. Object.defineProperty(Scene.prototype, "pointerY", {
  24579. /**
  24580. * Gets the current on-screen Y position of the pointer
  24581. */
  24582. get: function () {
  24583. return this._pointerY;
  24584. },
  24585. enumerable: true,
  24586. configurable: true
  24587. });
  24588. /**
  24589. * Gets the cached material (ie. the latest rendered one)
  24590. * @returns the cached material
  24591. */
  24592. Scene.prototype.getCachedMaterial = function () {
  24593. return this._cachedMaterial;
  24594. };
  24595. /**
  24596. * Gets the cached effect (ie. the latest rendered one)
  24597. * @returns the cached effect
  24598. */
  24599. Scene.prototype.getCachedEffect = function () {
  24600. return this._cachedEffect;
  24601. };
  24602. /**
  24603. * Gets the cached visibility state (ie. the latest rendered one)
  24604. * @returns the cached visibility state
  24605. */
  24606. Scene.prototype.getCachedVisibility = function () {
  24607. return this._cachedVisibility;
  24608. };
  24609. /**
  24610. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24611. * @param material defines the current material
  24612. * @param effect defines the current effect
  24613. * @param visibility defines the current visibility state
  24614. * @returns true if one parameter is not cached
  24615. */
  24616. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24617. if (visibility === void 0) { visibility = 1; }
  24618. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24619. };
  24620. /**
  24621. * Gets the bounding box renderer associated with the scene
  24622. * @returns a BoundingBoxRenderer
  24623. */
  24624. Scene.prototype.getBoundingBoxRenderer = function () {
  24625. if (!this._boundingBoxRenderer) {
  24626. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24627. }
  24628. return this._boundingBoxRenderer;
  24629. };
  24630. /**
  24631. * Gets the outline renderer associated with the scene
  24632. * @returns a OutlineRenderer
  24633. */
  24634. Scene.prototype.getOutlineRenderer = function () {
  24635. return this._outlineRenderer;
  24636. };
  24637. /**
  24638. * Gets the engine associated with the scene
  24639. * @returns an Engine
  24640. */
  24641. Scene.prototype.getEngine = function () {
  24642. return this._engine;
  24643. };
  24644. /**
  24645. * Gets the total number of vertices rendered per frame
  24646. * @returns the total number of vertices rendered per frame
  24647. */
  24648. Scene.prototype.getTotalVertices = function () {
  24649. return this._totalVertices.current;
  24650. };
  24651. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24652. /**
  24653. * Gets the performance counter for total vertices
  24654. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24655. */
  24656. get: function () {
  24657. return this._totalVertices;
  24658. },
  24659. enumerable: true,
  24660. configurable: true
  24661. });
  24662. /**
  24663. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24664. * @returns the total number of active indices rendered per frame
  24665. */
  24666. Scene.prototype.getActiveIndices = function () {
  24667. return this._activeIndices.current;
  24668. };
  24669. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24670. /**
  24671. * Gets the performance counter for active indices
  24672. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24673. */
  24674. get: function () {
  24675. return this._activeIndices;
  24676. },
  24677. enumerable: true,
  24678. configurable: true
  24679. });
  24680. /**
  24681. * Gets the total number of active particles rendered per frame
  24682. * @returns the total number of active particles rendered per frame
  24683. */
  24684. Scene.prototype.getActiveParticles = function () {
  24685. return this._activeParticles.current;
  24686. };
  24687. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24688. /**
  24689. * Gets the performance counter for active particles
  24690. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24691. */
  24692. get: function () {
  24693. return this._activeParticles;
  24694. },
  24695. enumerable: true,
  24696. configurable: true
  24697. });
  24698. /**
  24699. * Gets the total number of active bones rendered per frame
  24700. * @returns the total number of active bones rendered per frame
  24701. */
  24702. Scene.prototype.getActiveBones = function () {
  24703. return this._activeBones.current;
  24704. };
  24705. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24706. /**
  24707. * Gets the performance counter for active bones
  24708. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24709. */
  24710. get: function () {
  24711. return this._activeBones;
  24712. },
  24713. enumerable: true,
  24714. configurable: true
  24715. });
  24716. /** @hidden */
  24717. Scene.prototype.getInterFramePerfCounter = function () {
  24718. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24719. return 0;
  24720. };
  24721. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24722. /** @hidden */
  24723. get: function () {
  24724. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24725. return null;
  24726. },
  24727. enumerable: true,
  24728. configurable: true
  24729. });
  24730. /** @hidden */
  24731. Scene.prototype.getLastFrameDuration = function () {
  24732. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24733. return 0;
  24734. };
  24735. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24736. /** @hidden */
  24737. get: function () {
  24738. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24739. return null;
  24740. },
  24741. enumerable: true,
  24742. configurable: true
  24743. });
  24744. /** @hidden */
  24745. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24746. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24747. return 0;
  24748. };
  24749. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24750. /** @hidden */
  24751. get: function () {
  24752. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24753. return null;
  24754. },
  24755. enumerable: true,
  24756. configurable: true
  24757. });
  24758. /**
  24759. * Gets the array of active meshes
  24760. * @returns an array of AbstractMesh
  24761. */
  24762. Scene.prototype.getActiveMeshes = function () {
  24763. return this._activeMeshes;
  24764. };
  24765. /** @hidden */
  24766. Scene.prototype.getRenderTargetsDuration = function () {
  24767. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24768. return 0;
  24769. };
  24770. /** @hidden */
  24771. Scene.prototype.getRenderDuration = function () {
  24772. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24773. return 0;
  24774. };
  24775. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24776. /** @hidden */
  24777. get: function () {
  24778. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24779. return null;
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. /** @hidden */
  24785. Scene.prototype.getParticlesDuration = function () {
  24786. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24787. return 0;
  24788. };
  24789. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24790. /** @hidden */
  24791. get: function () {
  24792. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24793. return null;
  24794. },
  24795. enumerable: true,
  24796. configurable: true
  24797. });
  24798. /** @hidden */
  24799. Scene.prototype.getSpritesDuration = function () {
  24800. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24801. return 0;
  24802. };
  24803. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24804. /** @hidden */
  24805. get: function () {
  24806. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24807. return null;
  24808. },
  24809. enumerable: true,
  24810. configurable: true
  24811. });
  24812. /**
  24813. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24814. * @returns a number
  24815. */
  24816. Scene.prototype.getAnimationRatio = function () {
  24817. return this._animationRatio;
  24818. };
  24819. /**
  24820. * Gets an unique Id for the current frame
  24821. * @returns a number
  24822. */
  24823. Scene.prototype.getRenderId = function () {
  24824. return this._renderId;
  24825. };
  24826. /** Call this function if you want to manually increment the render Id*/
  24827. Scene.prototype.incrementRenderId = function () {
  24828. this._renderId++;
  24829. };
  24830. Scene.prototype._updatePointerPosition = function (evt) {
  24831. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24832. if (!canvasRect) {
  24833. return;
  24834. }
  24835. this._pointerX = evt.clientX - canvasRect.left;
  24836. this._pointerY = evt.clientY - canvasRect.top;
  24837. this._unTranslatedPointerX = this._pointerX;
  24838. this._unTranslatedPointerY = this._pointerY;
  24839. };
  24840. Scene.prototype._createUbo = function () {
  24841. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24842. this._sceneUbo.addUniform("viewProjection", 16);
  24843. this._sceneUbo.addUniform("view", 16);
  24844. };
  24845. Scene.prototype._createAlternateUbo = function () {
  24846. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24847. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24848. this._alternateSceneUbo.addUniform("view", 16);
  24849. };
  24850. // Pointers handling
  24851. /**
  24852. * Use this method to simulate a pointer move on a mesh
  24853. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24854. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24855. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24856. * @returns the current scene
  24857. */
  24858. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24859. var evt = new PointerEvent("pointermove", pointerEventInit);
  24860. return this._processPointerMove(pickResult, evt);
  24861. };
  24862. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24863. var canvas = this._engine.getRenderingCanvas();
  24864. if (!canvas) {
  24865. return this;
  24866. }
  24867. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24868. this.setPointerOverSprite(null);
  24869. this.setPointerOverMesh(pickResult.pickedMesh);
  24870. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24871. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24872. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24873. }
  24874. else {
  24875. canvas.style.cursor = this.hoverCursor;
  24876. }
  24877. }
  24878. else {
  24879. canvas.style.cursor = this.defaultCursor;
  24880. }
  24881. }
  24882. else {
  24883. this.setPointerOverMesh(null);
  24884. // Sprites
  24885. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24886. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24887. this.setPointerOverSprite(pickResult.pickedSprite);
  24888. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24889. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24890. }
  24891. else {
  24892. canvas.style.cursor = this.hoverCursor;
  24893. }
  24894. }
  24895. else {
  24896. this.setPointerOverSprite(null);
  24897. // Restore pointer
  24898. canvas.style.cursor = this.defaultCursor;
  24899. }
  24900. }
  24901. if (pickResult) {
  24902. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24903. if (this.onPointerMove) {
  24904. this.onPointerMove(evt, pickResult, type);
  24905. }
  24906. if (this.onPointerObservable.hasObservers()) {
  24907. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24908. this.onPointerObservable.notifyObservers(pi, type);
  24909. }
  24910. }
  24911. return this;
  24912. };
  24913. /**
  24914. * Use this method to simulate a pointer down on a mesh
  24915. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24916. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24917. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24918. * @returns the current scene
  24919. */
  24920. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24921. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24922. return this._processPointerDown(pickResult, evt);
  24923. };
  24924. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24925. var _this = this;
  24926. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24927. this._pickedDownMesh = pickResult.pickedMesh;
  24928. var actionManager = pickResult.pickedMesh.actionManager;
  24929. if (actionManager) {
  24930. if (actionManager.hasPickTriggers) {
  24931. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24932. switch (evt.button) {
  24933. case 0:
  24934. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24935. break;
  24936. case 1:
  24937. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24938. break;
  24939. case 2:
  24940. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24941. break;
  24942. }
  24943. }
  24944. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24945. window.setTimeout(function () {
  24946. 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);
  24947. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24948. if (_this._totalPointersPressed !== 0 &&
  24949. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24950. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24951. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24952. _this._startingPointerTime = 0;
  24953. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24954. }
  24955. }
  24956. }, Scene.LongPressDelay);
  24957. }
  24958. }
  24959. }
  24960. if (pickResult) {
  24961. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24962. if (this.onPointerDown) {
  24963. this.onPointerDown(evt, pickResult, type);
  24964. }
  24965. if (this.onPointerObservable.hasObservers()) {
  24966. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24967. this.onPointerObservable.notifyObservers(pi, type);
  24968. }
  24969. }
  24970. return this;
  24971. };
  24972. /**
  24973. * Use this method to simulate a pointer up on a mesh
  24974. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24975. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24976. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24977. * @returns the current scene
  24978. */
  24979. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24980. var evt = new PointerEvent("pointerup", pointerEventInit);
  24981. var clickInfo = new ClickInfo();
  24982. clickInfo.singleClick = true;
  24983. clickInfo.ignore = true;
  24984. return this._processPointerUp(pickResult, evt, clickInfo);
  24985. };
  24986. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24987. if (pickResult && pickResult && pickResult.pickedMesh) {
  24988. this._pickedUpMesh = pickResult.pickedMesh;
  24989. if (this._pickedDownMesh === this._pickedUpMesh) {
  24990. if (this.onPointerPick) {
  24991. this.onPointerPick(evt, pickResult);
  24992. }
  24993. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24994. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24995. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24996. this.onPointerObservable.notifyObservers(pi, type_1);
  24997. }
  24998. }
  24999. if (pickResult.pickedMesh.actionManager) {
  25000. if (clickInfo.ignore) {
  25001. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25002. }
  25003. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25004. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25005. }
  25006. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25007. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25008. }
  25009. }
  25010. }
  25011. if (this._pickedDownMesh &&
  25012. this._pickedDownMesh.actionManager &&
  25013. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25014. this._pickedDownMesh !== this._pickedUpMesh) {
  25015. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25016. }
  25017. var type = BABYLON.PointerEventTypes.POINTERUP;
  25018. if (this.onPointerObservable.hasObservers()) {
  25019. if (!clickInfo.ignore) {
  25020. if (!clickInfo.hasSwiped) {
  25021. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25022. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25023. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25024. this.onPointerObservable.notifyObservers(pi, type_2);
  25025. }
  25026. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25027. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25028. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25029. this.onPointerObservable.notifyObservers(pi, type_3);
  25030. }
  25031. }
  25032. }
  25033. else {
  25034. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25035. this.onPointerObservable.notifyObservers(pi, type);
  25036. }
  25037. }
  25038. if (this.onPointerUp) {
  25039. this.onPointerUp(evt, pickResult, type);
  25040. }
  25041. return this;
  25042. };
  25043. /**
  25044. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25045. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25046. * @returns true if the pointer was captured
  25047. */
  25048. Scene.prototype.isPointerCaptured = function (pointerId) {
  25049. if (pointerId === void 0) { pointerId = 0; }
  25050. return this._pointerCaptures[pointerId];
  25051. };
  25052. /**
  25053. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25054. * @param attachUp defines if you want to attach events to pointerup
  25055. * @param attachDown defines if you want to attach events to pointerdown
  25056. * @param attachMove defines if you want to attach events to pointermove
  25057. */
  25058. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25059. var _this = this;
  25060. if (attachUp === void 0) { attachUp = true; }
  25061. if (attachDown === void 0) { attachDown = true; }
  25062. if (attachMove === void 0) { attachMove = true; }
  25063. this._initActionManager = function (act, clickInfo) {
  25064. if (!_this._meshPickProceed) {
  25065. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25066. _this._currentPickResult = pickResult;
  25067. if (pickResult) {
  25068. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25069. }
  25070. _this._meshPickProceed = true;
  25071. }
  25072. return act;
  25073. };
  25074. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25075. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25076. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25077. btn !== _this._previousButtonPressed) {
  25078. _this._doubleClickOccured = false;
  25079. clickInfo.singleClick = true;
  25080. clickInfo.ignore = false;
  25081. cb(clickInfo, _this._currentPickResult);
  25082. }
  25083. };
  25084. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25085. var clickInfo = new ClickInfo();
  25086. _this._currentPickResult = null;
  25087. var act = null;
  25088. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25089. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25090. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25091. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25092. act = _this._initActionManager(act, clickInfo);
  25093. if (act)
  25094. checkPicking = act.hasPickTriggers;
  25095. }
  25096. if (checkPicking) {
  25097. var btn = evt.button;
  25098. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25099. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25100. if (!clickInfo.hasSwiped) {
  25101. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25102. if (!checkSingleClickImmediately) {
  25103. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25104. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25105. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25106. act = _this._initActionManager(act, clickInfo);
  25107. if (act)
  25108. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25109. }
  25110. }
  25111. if (checkSingleClickImmediately) {
  25112. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25113. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25114. btn !== _this._previousButtonPressed) {
  25115. clickInfo.singleClick = true;
  25116. cb(clickInfo, _this._currentPickResult);
  25117. }
  25118. }
  25119. // at least one double click is required to be check and exclusive double click is enabled
  25120. else {
  25121. // wait that no double click has been raised during the double click delay
  25122. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25123. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25124. }
  25125. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25126. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25127. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25128. act = _this._initActionManager(act, clickInfo);
  25129. if (act)
  25130. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25131. }
  25132. if (checkDoubleClick) {
  25133. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25134. if (btn === _this._previousButtonPressed &&
  25135. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25136. !_this._doubleClickOccured) {
  25137. // pointer has not moved for 2 clicks, it's a double click
  25138. if (!clickInfo.hasSwiped &&
  25139. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25140. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25141. _this._previousStartingPointerTime = 0;
  25142. _this._doubleClickOccured = true;
  25143. clickInfo.doubleClick = true;
  25144. clickInfo.ignore = false;
  25145. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25146. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25147. }
  25148. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25149. cb(clickInfo, _this._currentPickResult);
  25150. }
  25151. // if the two successive clicks are too far, it's just two simple clicks
  25152. else {
  25153. _this._doubleClickOccured = false;
  25154. _this._previousStartingPointerTime = _this._startingPointerTime;
  25155. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25156. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25157. _this._previousButtonPressed = btn;
  25158. if (Scene.ExclusiveDoubleClickMode) {
  25159. if (_this._previousDelayedSimpleClickTimeout) {
  25160. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25161. }
  25162. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25163. cb(clickInfo, _this._previousPickResult);
  25164. }
  25165. else {
  25166. cb(clickInfo, _this._currentPickResult);
  25167. }
  25168. }
  25169. }
  25170. // just the first click of the double has been raised
  25171. else {
  25172. _this._doubleClickOccured = false;
  25173. _this._previousStartingPointerTime = _this._startingPointerTime;
  25174. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25175. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25176. _this._previousButtonPressed = btn;
  25177. }
  25178. }
  25179. }
  25180. }
  25181. clickInfo.ignore = true;
  25182. cb(clickInfo, _this._currentPickResult);
  25183. };
  25184. this._spritePredicate = function (sprite) {
  25185. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25186. };
  25187. this._onPointerMove = function (evt) {
  25188. _this._updatePointerPosition(evt);
  25189. // PreObservable support
  25190. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25191. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25192. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25193. _this.onPrePointerObservable.notifyObservers(pi, type);
  25194. if (pi.skipOnPointerObservable) {
  25195. return;
  25196. }
  25197. }
  25198. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25199. return;
  25200. }
  25201. if (!_this.pointerMovePredicate) {
  25202. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25203. }
  25204. // Meshes
  25205. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25206. _this._processPointerMove(pickResult, evt);
  25207. };
  25208. this._onPointerDown = function (evt) {
  25209. _this._totalPointersPressed++;
  25210. _this._pickedDownMesh = null;
  25211. _this._meshPickProceed = false;
  25212. _this._updatePointerPosition(evt);
  25213. if (_this.preventDefaultOnPointerDown && canvas) {
  25214. evt.preventDefault();
  25215. canvas.focus();
  25216. }
  25217. // PreObservable support
  25218. if (_this.onPrePointerObservable.hasObservers()) {
  25219. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25220. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25221. _this.onPrePointerObservable.notifyObservers(pi, type);
  25222. if (pi.skipOnPointerObservable) {
  25223. return;
  25224. }
  25225. }
  25226. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25227. return;
  25228. }
  25229. _this._pointerCaptures[evt.pointerId] = true;
  25230. _this._startingPointerPosition.x = _this._pointerX;
  25231. _this._startingPointerPosition.y = _this._pointerY;
  25232. _this._startingPointerTime = Date.now();
  25233. if (!_this.pointerDownPredicate) {
  25234. _this.pointerDownPredicate = function (mesh) {
  25235. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25236. };
  25237. }
  25238. // Meshes
  25239. _this._pickedDownMesh = null;
  25240. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25241. _this._processPointerDown(pickResult, evt);
  25242. // Sprites
  25243. _this._pickedDownSprite = null;
  25244. if (_this.spriteManagers.length > 0) {
  25245. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25246. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25247. if (pickResult.pickedSprite.actionManager) {
  25248. _this._pickedDownSprite = pickResult.pickedSprite;
  25249. switch (evt.button) {
  25250. case 0:
  25251. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25252. break;
  25253. case 1:
  25254. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25255. break;
  25256. case 2:
  25257. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25258. break;
  25259. }
  25260. if (pickResult.pickedSprite.actionManager) {
  25261. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25262. }
  25263. }
  25264. }
  25265. }
  25266. };
  25267. this._onPointerUp = function (evt) {
  25268. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25269. return; // So we need to test it the pointer down was pressed before.
  25270. }
  25271. _this._totalPointersPressed--;
  25272. _this._pickedUpMesh = null;
  25273. _this._meshPickProceed = false;
  25274. _this._updatePointerPosition(evt);
  25275. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25276. // PreObservable support
  25277. if (_this.onPrePointerObservable.hasObservers()) {
  25278. if (!clickInfo.ignore) {
  25279. if (!clickInfo.hasSwiped) {
  25280. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25281. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25282. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25283. _this.onPrePointerObservable.notifyObservers(pi, type);
  25284. if (pi.skipOnPointerObservable) {
  25285. return;
  25286. }
  25287. }
  25288. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25289. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25290. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25291. _this.onPrePointerObservable.notifyObservers(pi, type);
  25292. if (pi.skipOnPointerObservable) {
  25293. return;
  25294. }
  25295. }
  25296. }
  25297. }
  25298. else {
  25299. var type = BABYLON.PointerEventTypes.POINTERUP;
  25300. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25301. _this.onPrePointerObservable.notifyObservers(pi, type);
  25302. if (pi.skipOnPointerObservable) {
  25303. return;
  25304. }
  25305. }
  25306. }
  25307. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25308. return;
  25309. }
  25310. _this._pointerCaptures[evt.pointerId] = false;
  25311. if (!_this.pointerUpPredicate) {
  25312. _this.pointerUpPredicate = function (mesh) {
  25313. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25314. };
  25315. }
  25316. // Meshes
  25317. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25318. _this._initActionManager(null, clickInfo);
  25319. }
  25320. if (!pickResult) {
  25321. pickResult = _this._currentPickResult;
  25322. }
  25323. _this._processPointerUp(pickResult, evt, clickInfo);
  25324. // Sprites
  25325. if (!clickInfo.ignore) {
  25326. if (_this.spriteManagers.length > 0) {
  25327. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25328. if (spritePickResult) {
  25329. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25330. if (spritePickResult.pickedSprite.actionManager) {
  25331. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25332. if (spritePickResult.pickedSprite.actionManager) {
  25333. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25334. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25335. }
  25336. }
  25337. }
  25338. }
  25339. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25340. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25341. }
  25342. }
  25343. }
  25344. }
  25345. _this._previousPickResult = _this._currentPickResult;
  25346. });
  25347. };
  25348. this._onKeyDown = function (evt) {
  25349. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25350. if (_this.onPreKeyboardObservable.hasObservers()) {
  25351. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25352. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25353. if (pi.skipOnPointerObservable) {
  25354. return;
  25355. }
  25356. }
  25357. if (_this.onKeyboardObservable.hasObservers()) {
  25358. var pi = new BABYLON.KeyboardInfo(type, evt);
  25359. _this.onKeyboardObservable.notifyObservers(pi, type);
  25360. }
  25361. if (_this.actionManager) {
  25362. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25363. }
  25364. };
  25365. this._onKeyUp = function (evt) {
  25366. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25367. if (_this.onPreKeyboardObservable.hasObservers()) {
  25368. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25369. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25370. if (pi.skipOnPointerObservable) {
  25371. return;
  25372. }
  25373. }
  25374. if (_this.onKeyboardObservable.hasObservers()) {
  25375. var pi = new BABYLON.KeyboardInfo(type, evt);
  25376. _this.onKeyboardObservable.notifyObservers(pi, type);
  25377. }
  25378. if (_this.actionManager) {
  25379. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25380. }
  25381. };
  25382. var engine = this.getEngine();
  25383. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25384. if (!canvas) {
  25385. return;
  25386. }
  25387. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25388. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25389. });
  25390. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25391. if (!canvas) {
  25392. return;
  25393. }
  25394. canvas.removeEventListener("keydown", _this._onKeyDown);
  25395. canvas.removeEventListener("keyup", _this._onKeyUp);
  25396. });
  25397. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25398. var canvas = this._engine.getRenderingCanvas();
  25399. if (!canvas) {
  25400. return;
  25401. }
  25402. if (attachMove) {
  25403. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25404. // Wheel
  25405. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25406. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25407. }
  25408. if (attachDown) {
  25409. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25410. }
  25411. if (attachUp) {
  25412. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25413. }
  25414. canvas.tabIndex = 1;
  25415. };
  25416. /** Detaches all event handlers*/
  25417. Scene.prototype.detachControl = function () {
  25418. var engine = this.getEngine();
  25419. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25420. var canvas = engine.getRenderingCanvas();
  25421. if (!canvas) {
  25422. return;
  25423. }
  25424. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25425. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25426. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25427. if (this._onCanvasBlurObserver) {
  25428. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25429. }
  25430. if (this._onCanvasFocusObserver) {
  25431. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25432. }
  25433. // Wheel
  25434. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25435. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25436. // Keyboard
  25437. canvas.removeEventListener("keydown", this._onKeyDown);
  25438. canvas.removeEventListener("keyup", this._onKeyUp);
  25439. // Observables
  25440. this.onKeyboardObservable.clear();
  25441. this.onPreKeyboardObservable.clear();
  25442. this.onPointerObservable.clear();
  25443. this.onPrePointerObservable.clear();
  25444. };
  25445. /**
  25446. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25447. * Delay loaded resources are not taking in account
  25448. * @return true if all required resources are ready
  25449. */
  25450. Scene.prototype.isReady = function () {
  25451. if (this._isDisposed) {
  25452. return false;
  25453. }
  25454. if (this._pendingData.length > 0) {
  25455. return false;
  25456. }
  25457. var index;
  25458. var engine = this.getEngine();
  25459. // Geometries
  25460. for (index = 0; index < this._geometries.length; index++) {
  25461. var geometry = this._geometries[index];
  25462. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25463. return false;
  25464. }
  25465. }
  25466. // Meshes
  25467. for (index = 0; index < this.meshes.length; index++) {
  25468. var mesh = this.meshes[index];
  25469. if (!mesh.isEnabled()) {
  25470. continue;
  25471. }
  25472. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25473. continue;
  25474. }
  25475. if (!mesh.isReady(true)) {
  25476. return false;
  25477. }
  25478. // Effect layers
  25479. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25480. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25481. var layer = _a[_i];
  25482. if (!layer.hasMesh(mesh)) {
  25483. continue;
  25484. }
  25485. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25486. var subMesh = _c[_b];
  25487. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25488. return false;
  25489. }
  25490. }
  25491. }
  25492. }
  25493. // Post-processes
  25494. if (this.activeCameras && this.activeCameras.length > 0) {
  25495. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25496. var camera = _e[_d];
  25497. if (!camera.isReady(true)) {
  25498. return false;
  25499. }
  25500. }
  25501. }
  25502. else if (this.activeCamera) {
  25503. if (!this.activeCamera.isReady(true)) {
  25504. return false;
  25505. }
  25506. }
  25507. // Particles
  25508. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25509. var particleSystem = _g[_f];
  25510. if (!particleSystem.isReady()) {
  25511. return false;
  25512. }
  25513. }
  25514. return true;
  25515. };
  25516. /** Resets all cached information relative to material (including effect and visibility) */
  25517. Scene.prototype.resetCachedMaterial = function () {
  25518. this._cachedMaterial = null;
  25519. this._cachedEffect = null;
  25520. this._cachedVisibility = null;
  25521. };
  25522. /**
  25523. * Registers a function to be called before every frame render
  25524. * @param func defines the function to register
  25525. */
  25526. Scene.prototype.registerBeforeRender = function (func) {
  25527. this.onBeforeRenderObservable.add(func);
  25528. };
  25529. /**
  25530. * Unregisters a function called before every frame render
  25531. * @param func defines the function to unregister
  25532. */
  25533. Scene.prototype.unregisterBeforeRender = function (func) {
  25534. this.onBeforeRenderObservable.removeCallback(func);
  25535. };
  25536. /**
  25537. * Registers a function to be called after every frame render
  25538. * @param func defines the function to register
  25539. */
  25540. Scene.prototype.registerAfterRender = function (func) {
  25541. this.onAfterRenderObservable.add(func);
  25542. };
  25543. /**
  25544. * Unregisters a function called after every frame render
  25545. * @param func defines the function to unregister
  25546. */
  25547. Scene.prototype.unregisterAfterRender = function (func) {
  25548. this.onAfterRenderObservable.removeCallback(func);
  25549. };
  25550. Scene.prototype._executeOnceBeforeRender = function (func) {
  25551. var _this = this;
  25552. var execFunc = function () {
  25553. func();
  25554. setTimeout(function () {
  25555. _this.unregisterBeforeRender(execFunc);
  25556. });
  25557. };
  25558. this.registerBeforeRender(execFunc);
  25559. };
  25560. /**
  25561. * The provided function will run before render once and will be disposed afterwards.
  25562. * A timeout delay can be provided so that the function will be executed in N ms.
  25563. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25564. * @param func The function to be executed.
  25565. * @param timeout optional delay in ms
  25566. */
  25567. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25568. var _this = this;
  25569. if (timeout !== undefined) {
  25570. setTimeout(function () {
  25571. _this._executeOnceBeforeRender(func);
  25572. }, timeout);
  25573. }
  25574. else {
  25575. this._executeOnceBeforeRender(func);
  25576. }
  25577. };
  25578. /** @hidden */
  25579. Scene.prototype._addPendingData = function (data) {
  25580. this._pendingData.push(data);
  25581. };
  25582. /** @hidden */
  25583. Scene.prototype._removePendingData = function (data) {
  25584. var wasLoading = this.isLoading;
  25585. var index = this._pendingData.indexOf(data);
  25586. if (index !== -1) {
  25587. this._pendingData.splice(index, 1);
  25588. }
  25589. if (wasLoading && !this.isLoading) {
  25590. this.onDataLoadedObservable.notifyObservers(this);
  25591. }
  25592. };
  25593. /**
  25594. * Returns the number of items waiting to be loaded
  25595. * @returns the number of items waiting to be loaded
  25596. */
  25597. Scene.prototype.getWaitingItemsCount = function () {
  25598. return this._pendingData.length;
  25599. };
  25600. Object.defineProperty(Scene.prototype, "isLoading", {
  25601. /**
  25602. * Returns a boolean indicating if the scene is still loading data
  25603. */
  25604. get: function () {
  25605. return this._pendingData.length > 0;
  25606. },
  25607. enumerable: true,
  25608. configurable: true
  25609. });
  25610. /**
  25611. * Registers a function to be executed when the scene is ready
  25612. * @param {Function} func - the function to be executed
  25613. */
  25614. Scene.prototype.executeWhenReady = function (func) {
  25615. var _this = this;
  25616. this.onReadyObservable.add(func);
  25617. if (this._executeWhenReadyTimeoutId !== -1) {
  25618. return;
  25619. }
  25620. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25621. _this._checkIsReady();
  25622. }, 150);
  25623. };
  25624. /**
  25625. * Returns a promise that resolves when the scene is ready
  25626. * @returns A promise that resolves when the scene is ready
  25627. */
  25628. Scene.prototype.whenReadyAsync = function () {
  25629. var _this = this;
  25630. return new Promise(function (resolve) {
  25631. _this.executeWhenReady(function () {
  25632. resolve();
  25633. });
  25634. });
  25635. };
  25636. /** @hidden */
  25637. Scene.prototype._checkIsReady = function () {
  25638. var _this = this;
  25639. if (this.isReady()) {
  25640. this.onReadyObservable.notifyObservers(this);
  25641. this.onReadyObservable.clear();
  25642. this._executeWhenReadyTimeoutId = -1;
  25643. return;
  25644. }
  25645. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25646. _this._checkIsReady();
  25647. }, 150);
  25648. };
  25649. // Animations
  25650. /**
  25651. * Will start the animation sequence of a given target
  25652. * @param target defines the target
  25653. * @param from defines from which frame should animation start
  25654. * @param to defines until which frame should animation run.
  25655. * @param weight defines the weight to apply to the animation (1.0 by default)
  25656. * @param loop defines if the animation loops
  25657. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25658. * @param onAnimationEnd defines the function to be executed when the animation ends
  25659. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25660. * @returns the animatable object created for this animation
  25661. */
  25662. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25663. if (weight === void 0) { weight = 1.0; }
  25664. if (speedRatio === void 0) { speedRatio = 1.0; }
  25665. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25666. returnedAnimatable.weight = weight;
  25667. return returnedAnimatable;
  25668. };
  25669. /**
  25670. * Will start the animation sequence of a given target
  25671. * @param target defines the target
  25672. * @param from defines from which frame should animation start
  25673. * @param to defines until which frame should animation run.
  25674. * @param loop defines if the animation loops
  25675. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25676. * @param onAnimationEnd defines the function to be executed when the animation ends
  25677. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25678. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25679. * @returns the animatable object created for this animation
  25680. */
  25681. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25682. if (speedRatio === void 0) { speedRatio = 1.0; }
  25683. if (stopCurrent === void 0) { stopCurrent = true; }
  25684. if (from > to && speedRatio > 0) {
  25685. speedRatio *= -1;
  25686. }
  25687. if (stopCurrent) {
  25688. this.stopAnimation(target);
  25689. }
  25690. if (!animatable) {
  25691. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25692. }
  25693. // Local animations
  25694. if (target.animations) {
  25695. animatable.appendAnimations(target, target.animations);
  25696. }
  25697. // Children animations
  25698. if (target.getAnimatables) {
  25699. var animatables = target.getAnimatables();
  25700. for (var index = 0; index < animatables.length; index++) {
  25701. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25702. }
  25703. }
  25704. animatable.reset();
  25705. return animatable;
  25706. };
  25707. /**
  25708. * Begin a new animation on a given node
  25709. * @param target defines the target where the animation will take place
  25710. * @param animations defines the list of animations to start
  25711. * @param from defines the initial value
  25712. * @param to defines the final value
  25713. * @param loop defines if you want animation to loop (off by default)
  25714. * @param speedRatio defines the speed ratio to apply to all animations
  25715. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25716. * @returns the list of created animatables
  25717. */
  25718. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25719. if (speedRatio === undefined) {
  25720. speedRatio = 1.0;
  25721. }
  25722. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25723. return animatable;
  25724. };
  25725. /**
  25726. * Begin a new animation on a given node and its hierarchy
  25727. * @param target defines the root node where the animation will take place
  25728. * @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.
  25729. * @param animations defines the list of animations to start
  25730. * @param from defines the initial value
  25731. * @param to defines the final value
  25732. * @param loop defines if you want animation to loop (off by default)
  25733. * @param speedRatio defines the speed ratio to apply to all animations
  25734. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25735. * @returns the list of animatables created for all nodes
  25736. */
  25737. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25738. var children = target.getDescendants(directDescendantsOnly);
  25739. var result = [];
  25740. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25741. var child = children_1[_i];
  25742. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25743. }
  25744. return result;
  25745. };
  25746. /**
  25747. * Gets the animatable associated with a specific target
  25748. * @param target defines the target of the animatable
  25749. * @returns the required animatable if found
  25750. */
  25751. Scene.prototype.getAnimatableByTarget = function (target) {
  25752. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25753. if (this._activeAnimatables[index].target === target) {
  25754. return this._activeAnimatables[index];
  25755. }
  25756. }
  25757. return null;
  25758. };
  25759. /**
  25760. * Gets all animatables associated with a given target
  25761. * @param target defines the target to look animatables for
  25762. * @returns an array of Animatables
  25763. */
  25764. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25765. var result = [];
  25766. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25767. if (this._activeAnimatables[index].target === target) {
  25768. result.push(this._activeAnimatables[index]);
  25769. }
  25770. }
  25771. return result;
  25772. };
  25773. Object.defineProperty(Scene.prototype, "animatables", {
  25774. /**
  25775. * Gets all animatable attached to the scene
  25776. */
  25777. get: function () {
  25778. return this._activeAnimatables;
  25779. },
  25780. enumerable: true,
  25781. configurable: true
  25782. });
  25783. /**
  25784. * Will stop the animation of the given target
  25785. * @param target - the target
  25786. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25787. */
  25788. Scene.prototype.stopAnimation = function (target, animationName) {
  25789. var animatables = this.getAllAnimatablesByTarget(target);
  25790. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25791. var animatable = animatables_1[_i];
  25792. animatable.stop(animationName);
  25793. }
  25794. };
  25795. /**
  25796. * Stops and removes all animations that have been applied to the scene
  25797. */
  25798. Scene.prototype.stopAllAnimations = function () {
  25799. if (this._activeAnimatables) {
  25800. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25801. this._activeAnimatables[i].stop();
  25802. }
  25803. this._activeAnimatables = [];
  25804. }
  25805. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25806. var group = _a[_i];
  25807. group.stop();
  25808. }
  25809. };
  25810. Scene.prototype._animate = function () {
  25811. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25812. return;
  25813. }
  25814. // Getting time
  25815. var now = BABYLON.Tools.Now;
  25816. if (!this._animationTimeLast) {
  25817. if (this._pendingData.length > 0) {
  25818. return;
  25819. }
  25820. this._animationTimeLast = now;
  25821. }
  25822. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25823. this._animationTime += deltaTime;
  25824. this._animationTimeLast = now;
  25825. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25826. this._activeAnimatables[index]._animate(this._animationTime);
  25827. }
  25828. // Late animation bindings
  25829. this._processLateAnimationBindings();
  25830. };
  25831. /** @hidden */
  25832. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25833. var target = runtimeAnimation.target;
  25834. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25835. if (!target._lateAnimationHolders) {
  25836. target._lateAnimationHolders = {};
  25837. }
  25838. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25839. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25840. totalWeight: 0,
  25841. animations: [],
  25842. originalValue: originalValue
  25843. };
  25844. }
  25845. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25846. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25847. };
  25848. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25849. var normalizer = 1.0;
  25850. var finalPosition = BABYLON.Tmp.Vector3[0];
  25851. var finalScaling = BABYLON.Tmp.Vector3[1];
  25852. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25853. var startIndex = 0;
  25854. var originalAnimation = holder.animations[0];
  25855. var originalValue = holder.originalValue;
  25856. var scale = 1;
  25857. if (holder.totalWeight < 1.0) {
  25858. // We need to mix the original value in
  25859. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25860. scale = 1.0 - holder.totalWeight;
  25861. }
  25862. else {
  25863. startIndex = 1;
  25864. // We need to normalize the weights
  25865. normalizer = holder.totalWeight;
  25866. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25867. scale = originalAnimation.weight / normalizer;
  25868. if (scale == 1) {
  25869. return originalAnimation.currentValue;
  25870. }
  25871. }
  25872. finalScaling.scaleInPlace(scale);
  25873. finalPosition.scaleInPlace(scale);
  25874. finalQuaternion.scaleInPlace(scale);
  25875. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25876. var runtimeAnimation = holder.animations[animIndex];
  25877. var scale = runtimeAnimation.weight / normalizer;
  25878. var currentPosition = BABYLON.Tmp.Vector3[2];
  25879. var currentScaling = BABYLON.Tmp.Vector3[3];
  25880. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25881. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25882. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25883. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25884. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25885. }
  25886. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25887. return originalAnimation._workValue;
  25888. };
  25889. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25890. var originalAnimation = holder.animations[0];
  25891. var originalValue = holder.originalValue;
  25892. if (holder.animations.length === 1) {
  25893. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25894. }
  25895. var normalizer = 1.0;
  25896. var quaternions;
  25897. var weights;
  25898. if (holder.totalWeight < 1.0) {
  25899. var scale = 1.0 - holder.totalWeight;
  25900. quaternions = [];
  25901. weights = [];
  25902. quaternions.push(originalValue);
  25903. weights.push(scale);
  25904. }
  25905. else {
  25906. if (holder.animations.length === 2) { // Slerp as soon as we can
  25907. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25908. }
  25909. quaternions = [];
  25910. weights = [];
  25911. normalizer = holder.totalWeight;
  25912. }
  25913. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25914. var runtimeAnimation = holder.animations[animIndex];
  25915. quaternions.push(runtimeAnimation.currentValue);
  25916. weights.push(runtimeAnimation.weight / normalizer);
  25917. }
  25918. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25919. var cumulativeAmount = 0;
  25920. var cumulativeQuaternion = null;
  25921. for (var index = 0; index < quaternions.length;) {
  25922. if (!cumulativeQuaternion) {
  25923. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25924. cumulativeAmount = weights[index] + weights[index + 1];
  25925. index += 2;
  25926. continue;
  25927. }
  25928. cumulativeAmount += weights[index];
  25929. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25930. index++;
  25931. }
  25932. return cumulativeQuaternion;
  25933. };
  25934. Scene.prototype._processLateAnimationBindings = function () {
  25935. if (!this._registeredForLateAnimationBindings.length) {
  25936. return;
  25937. }
  25938. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25939. var target = this._registeredForLateAnimationBindings.data[index];
  25940. for (var path in target._lateAnimationHolders) {
  25941. var holder = target._lateAnimationHolders[path];
  25942. var originalAnimation = holder.animations[0];
  25943. var originalValue = holder.originalValue;
  25944. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25945. var finalValue = void 0;
  25946. if (matrixDecomposeMode) {
  25947. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25948. }
  25949. else {
  25950. var quaternionMode = originalValue.w !== undefined;
  25951. if (quaternionMode) {
  25952. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25953. }
  25954. else {
  25955. var startIndex = 0;
  25956. var normalizer = 1.0;
  25957. if (holder.totalWeight < 1.0) {
  25958. // We need to mix the original value in
  25959. if (originalValue.scale) {
  25960. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25961. }
  25962. else {
  25963. finalValue = originalValue * (1.0 - holder.totalWeight);
  25964. }
  25965. }
  25966. else {
  25967. // We need to normalize the weights
  25968. normalizer = holder.totalWeight;
  25969. var scale_1 = originalAnimation.weight / normalizer;
  25970. if (scale_1 !== 1) {
  25971. if (originalAnimation.currentValue.scale) {
  25972. finalValue = originalAnimation.currentValue.scale(scale_1);
  25973. }
  25974. else {
  25975. finalValue = originalAnimation.currentValue * scale_1;
  25976. }
  25977. }
  25978. else {
  25979. finalValue = originalAnimation.currentValue;
  25980. }
  25981. startIndex = 1;
  25982. }
  25983. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25984. var runtimeAnimation = holder.animations[animIndex];
  25985. var scale = runtimeAnimation.weight / normalizer;
  25986. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25987. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25988. }
  25989. else {
  25990. finalValue += runtimeAnimation.currentValue * scale;
  25991. }
  25992. }
  25993. }
  25994. }
  25995. target[path] = finalValue;
  25996. }
  25997. target._lateAnimationHolders = {};
  25998. }
  25999. this._registeredForLateAnimationBindings.reset();
  26000. };
  26001. // Matrix
  26002. /** @hidden */
  26003. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26004. this._useAlternateCameraConfiguration = active;
  26005. };
  26006. /**
  26007. * Gets the current view matrix
  26008. * @returns a Matrix
  26009. */
  26010. Scene.prototype.getViewMatrix = function () {
  26011. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26012. };
  26013. /**
  26014. * Gets the current projection matrix
  26015. * @returns a Matrix
  26016. */
  26017. Scene.prototype.getProjectionMatrix = function () {
  26018. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26019. };
  26020. /**
  26021. * Gets the current transform matrix
  26022. * @returns a Matrix made of View * Projection
  26023. */
  26024. Scene.prototype.getTransformMatrix = function () {
  26025. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26026. };
  26027. /**
  26028. * Sets the current transform matrix
  26029. * @param view defines the View matrix to use
  26030. * @param projection defines the Projection matrix to use
  26031. */
  26032. Scene.prototype.setTransformMatrix = function (view, projection) {
  26033. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26034. return;
  26035. }
  26036. this._viewUpdateFlag = view.updateFlag;
  26037. this._projectionUpdateFlag = projection.updateFlag;
  26038. this._viewMatrix = view;
  26039. this._projectionMatrix = projection;
  26040. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26041. // Update frustum
  26042. if (!this._frustumPlanes) {
  26043. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26044. }
  26045. else {
  26046. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26047. }
  26048. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26049. var otherCamera = this.activeCamera._alternateCamera;
  26050. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26051. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26052. }
  26053. if (this._sceneUbo.useUbo) {
  26054. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26055. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26056. this._sceneUbo.update();
  26057. }
  26058. };
  26059. /** @hidden */
  26060. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26061. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26062. return;
  26063. }
  26064. this._alternateViewUpdateFlag = view.updateFlag;
  26065. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26066. this._alternateViewMatrix = view;
  26067. this._alternateProjectionMatrix = projection;
  26068. if (!this._alternateTransformMatrix) {
  26069. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26070. }
  26071. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26072. if (!this._alternateSceneUbo) {
  26073. this._createAlternateUbo();
  26074. }
  26075. if (this._alternateSceneUbo.useUbo) {
  26076. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26077. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26078. this._alternateSceneUbo.update();
  26079. }
  26080. };
  26081. /**
  26082. * Gets the uniform buffer used to store scene data
  26083. * @returns a UniformBuffer
  26084. */
  26085. Scene.prototype.getSceneUniformBuffer = function () {
  26086. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26087. };
  26088. /**
  26089. * Gets an unique (relatively to the current scene) Id
  26090. * @returns an unique number for the scene
  26091. */
  26092. Scene.prototype.getUniqueId = function () {
  26093. var result = Scene._uniqueIdCounter;
  26094. Scene._uniqueIdCounter++;
  26095. return result;
  26096. };
  26097. /**
  26098. * Add a mesh to the list of scene's meshes
  26099. * @param newMesh defines the mesh to add
  26100. */
  26101. Scene.prototype.addMesh = function (newMesh) {
  26102. this.meshes.push(newMesh);
  26103. //notify the collision coordinator
  26104. if (this.collisionCoordinator) {
  26105. this.collisionCoordinator.onMeshAdded(newMesh);
  26106. }
  26107. newMesh._resyncLightSources();
  26108. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26109. };
  26110. /**
  26111. * Remove a mesh for the list of scene's meshes
  26112. * @param toRemove defines the mesh to remove
  26113. * @param recursive if all child meshes should also be removed from the scene
  26114. * @returns the index where the mesh was in the mesh list
  26115. */
  26116. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26117. var _this = this;
  26118. if (recursive === void 0) { recursive = false; }
  26119. var index = this.meshes.indexOf(toRemove);
  26120. if (index !== -1) {
  26121. // Remove from the scene if mesh found
  26122. this.meshes.splice(index, 1);
  26123. }
  26124. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26125. if (recursive) {
  26126. toRemove.getChildMeshes().forEach(function (m) {
  26127. _this.removeMesh(m);
  26128. });
  26129. }
  26130. return index;
  26131. };
  26132. /**
  26133. * Add a transform node to the list of scene's transform nodes
  26134. * @param newTransformNode defines the transform node to add
  26135. */
  26136. Scene.prototype.addTransformNode = function (newTransformNode) {
  26137. this.transformNodes.push(newTransformNode);
  26138. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26139. };
  26140. /**
  26141. * Remove a transform node for the list of scene's transform nodes
  26142. * @param toRemove defines the transform node to remove
  26143. * @returns the index where the transform node was in the transform node list
  26144. */
  26145. Scene.prototype.removeTransformNode = function (toRemove) {
  26146. var index = this.transformNodes.indexOf(toRemove);
  26147. if (index !== -1) {
  26148. // Remove from the scene if found
  26149. this.transformNodes.splice(index, 1);
  26150. }
  26151. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26152. return index;
  26153. };
  26154. /**
  26155. * Remove a skeleton for the list of scene's skeletons
  26156. * @param toRemove defines the skeleton to remove
  26157. * @returns the index where the skeleton was in the skeleton list
  26158. */
  26159. Scene.prototype.removeSkeleton = function (toRemove) {
  26160. var index = this.skeletons.indexOf(toRemove);
  26161. if (index !== -1) {
  26162. // Remove from the scene if found
  26163. this.skeletons.splice(index, 1);
  26164. }
  26165. return index;
  26166. };
  26167. /**
  26168. * Remove a morph target for the list of scene's morph targets
  26169. * @param toRemove defines the morph target to remove
  26170. * @returns the index where the morph target was in the morph target list
  26171. */
  26172. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26173. var index = this.morphTargetManagers.indexOf(toRemove);
  26174. if (index !== -1) {
  26175. // Remove from the scene if found
  26176. this.morphTargetManagers.splice(index, 1);
  26177. }
  26178. return index;
  26179. };
  26180. /**
  26181. * Remove a light for the list of scene's lights
  26182. * @param toRemove defines the light to remove
  26183. * @returns the index where the light was in the light list
  26184. */
  26185. Scene.prototype.removeLight = function (toRemove) {
  26186. var index = this.lights.indexOf(toRemove);
  26187. if (index !== -1) {
  26188. // Remove from meshes
  26189. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26190. var mesh = _a[_i];
  26191. mesh._removeLightSource(toRemove);
  26192. }
  26193. // Remove from the scene if mesh found
  26194. this.lights.splice(index, 1);
  26195. this.sortLightsByPriority();
  26196. }
  26197. this.onLightRemovedObservable.notifyObservers(toRemove);
  26198. return index;
  26199. };
  26200. /**
  26201. * Remove a camera for the list of scene's cameras
  26202. * @param toRemove defines the camera to remove
  26203. * @returns the index where the camera was in the camera list
  26204. */
  26205. Scene.prototype.removeCamera = function (toRemove) {
  26206. var index = this.cameras.indexOf(toRemove);
  26207. if (index !== -1) {
  26208. // Remove from the scene if mesh found
  26209. this.cameras.splice(index, 1);
  26210. }
  26211. // Remove from activeCameras
  26212. var index2 = this.activeCameras.indexOf(toRemove);
  26213. if (index2 !== -1) {
  26214. // Remove from the scene if mesh found
  26215. this.activeCameras.splice(index2, 1);
  26216. }
  26217. // Reset the activeCamera
  26218. if (this.activeCamera === toRemove) {
  26219. if (this.cameras.length > 0) {
  26220. this.activeCamera = this.cameras[0];
  26221. }
  26222. else {
  26223. this.activeCamera = null;
  26224. }
  26225. }
  26226. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26227. return index;
  26228. };
  26229. /**
  26230. * Remove a particle system for the list of scene's particle systems
  26231. * @param toRemove defines the particle system to remove
  26232. * @returns the index where the particle system was in the particle system list
  26233. */
  26234. Scene.prototype.removeParticleSystem = function (toRemove) {
  26235. var index = this.particleSystems.indexOf(toRemove);
  26236. if (index !== -1) {
  26237. this.particleSystems.splice(index, 1);
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Remove a animation for the list of scene's animations
  26243. * @param toRemove defines the animation to remove
  26244. * @returns the index where the animation was in the animation list
  26245. */
  26246. Scene.prototype.removeAnimation = function (toRemove) {
  26247. var index = this.animations.indexOf(toRemove);
  26248. if (index !== -1) {
  26249. this.animations.splice(index, 1);
  26250. }
  26251. return index;
  26252. };
  26253. /**
  26254. * Removes the given animation group from this scene.
  26255. * @param toRemove The animation group to remove
  26256. * @returns The index of the removed animation group
  26257. */
  26258. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26259. var index = this.animationGroups.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. this.animationGroups.splice(index, 1);
  26262. }
  26263. return index;
  26264. };
  26265. /**
  26266. * Removes the given multi-material from this scene.
  26267. * @param toRemove The multi-material to remove
  26268. * @returns The index of the removed multi-material
  26269. */
  26270. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26271. var index = this.multiMaterials.indexOf(toRemove);
  26272. if (index !== -1) {
  26273. this.multiMaterials.splice(index, 1);
  26274. }
  26275. return index;
  26276. };
  26277. /**
  26278. * Removes the given material from this scene.
  26279. * @param toRemove The material to remove
  26280. * @returns The index of the removed material
  26281. */
  26282. Scene.prototype.removeMaterial = function (toRemove) {
  26283. var index = this.materials.indexOf(toRemove);
  26284. if (index !== -1) {
  26285. this.materials.splice(index, 1);
  26286. }
  26287. return index;
  26288. };
  26289. /**
  26290. * Removes the given lens flare system from this scene.
  26291. * @param toRemove The lens flare system to remove
  26292. * @returns The index of the removed lens flare system
  26293. */
  26294. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26295. var index = this.lensFlareSystems.indexOf(toRemove);
  26296. if (index !== -1) {
  26297. this.lensFlareSystems.splice(index, 1);
  26298. }
  26299. return index;
  26300. };
  26301. /**
  26302. * Removes the given action manager from this scene.
  26303. * @param toRemove The action manager to remove
  26304. * @returns The index of the removed action manager
  26305. */
  26306. Scene.prototype.removeActionManager = function (toRemove) {
  26307. var index = this._actionManagers.indexOf(toRemove);
  26308. if (index !== -1) {
  26309. this._actionManagers.splice(index, 1);
  26310. }
  26311. return index;
  26312. };
  26313. /**
  26314. * Removes the given effect layer from this scene.
  26315. * @param toRemove defines the effect layer to remove
  26316. * @returns the index of the removed effect layer
  26317. */
  26318. Scene.prototype.removeEffectLayer = function (toRemove) {
  26319. var index = this.effectLayers.indexOf(toRemove);
  26320. if (index !== -1) {
  26321. this.effectLayers.splice(index, 1);
  26322. }
  26323. return index;
  26324. };
  26325. /**
  26326. * Removes the given texture from this scene.
  26327. * @param toRemove The texture to remove
  26328. * @returns The index of the removed texture
  26329. */
  26330. Scene.prototype.removeTexture = function (toRemove) {
  26331. var index = this.textures.indexOf(toRemove);
  26332. if (index !== -1) {
  26333. this.textures.splice(index, 1);
  26334. }
  26335. return index;
  26336. };
  26337. /**
  26338. * Adds the given light to this scene
  26339. * @param newLight The light to add
  26340. */
  26341. Scene.prototype.addLight = function (newLight) {
  26342. this.lights.push(newLight);
  26343. this.sortLightsByPriority();
  26344. // Add light to all meshes (To support if the light is removed and then readded)
  26345. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26346. var mesh = _a[_i];
  26347. if (mesh._lightSources.indexOf(newLight) === -1) {
  26348. mesh._lightSources.push(newLight);
  26349. mesh._resyncLightSources();
  26350. }
  26351. }
  26352. this.onNewLightAddedObservable.notifyObservers(newLight);
  26353. };
  26354. /**
  26355. * Sorts the list list based on light priorities
  26356. */
  26357. Scene.prototype.sortLightsByPriority = function () {
  26358. if (this.requireLightSorting) {
  26359. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26360. }
  26361. };
  26362. /**
  26363. * Adds the given camera to this scene
  26364. * @param newCamera The camera to add
  26365. */
  26366. Scene.prototype.addCamera = function (newCamera) {
  26367. this.cameras.push(newCamera);
  26368. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26369. };
  26370. /**
  26371. * Adds the given skeleton to this scene
  26372. * @param newSkeleton The skeleton to add
  26373. */
  26374. Scene.prototype.addSkeleton = function (newSkeleton) {
  26375. this.skeletons.push(newSkeleton);
  26376. };
  26377. /**
  26378. * Adds the given particle system to this scene
  26379. * @param newParticleSystem The particle system to add
  26380. */
  26381. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26382. this.particleSystems.push(newParticleSystem);
  26383. };
  26384. /**
  26385. * Adds the given animation to this scene
  26386. * @param newAnimation The animation to add
  26387. */
  26388. Scene.prototype.addAnimation = function (newAnimation) {
  26389. this.animations.push(newAnimation);
  26390. };
  26391. /**
  26392. * Adds the given animation group to this scene.
  26393. * @param newAnimationGroup The animation group to add
  26394. */
  26395. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26396. this.animationGroups.push(newAnimationGroup);
  26397. };
  26398. /**
  26399. * Adds the given multi-material to this scene
  26400. * @param newMultiMaterial The multi-material to add
  26401. */
  26402. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26403. this.multiMaterials.push(newMultiMaterial);
  26404. };
  26405. /**
  26406. * Adds the given material to this scene
  26407. * @param newMaterial The material to add
  26408. */
  26409. Scene.prototype.addMaterial = function (newMaterial) {
  26410. this.materials.push(newMaterial);
  26411. };
  26412. /**
  26413. * Adds the given morph target to this scene
  26414. * @param newMorphTargetManager The morph target to add
  26415. */
  26416. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26417. this.morphTargetManagers.push(newMorphTargetManager);
  26418. };
  26419. /**
  26420. * Adds the given geometry to this scene
  26421. * @param newGeometry The geometry to add
  26422. */
  26423. Scene.prototype.addGeometry = function (newGeometry) {
  26424. this._geometries.push(newGeometry);
  26425. };
  26426. /**
  26427. * Adds the given lens flare system to this scene
  26428. * @param newLensFlareSystem The lens flare system to add
  26429. */
  26430. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26431. this.lensFlareSystems.push(newLensFlareSystem);
  26432. };
  26433. /**
  26434. * Adds the given effect layer to this scene
  26435. * @param newEffectLayer defines the effect layer to add
  26436. */
  26437. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26438. this.effectLayers.push(newEffectLayer);
  26439. };
  26440. /**
  26441. * Adds the given action manager to this scene
  26442. * @param newActionManager The action manager to add
  26443. */
  26444. Scene.prototype.addActionManager = function (newActionManager) {
  26445. this._actionManagers.push(newActionManager);
  26446. };
  26447. /**
  26448. * Adds the given texture to this scene.
  26449. * @param newTexture The texture to add
  26450. */
  26451. Scene.prototype.addTexture = function (newTexture) {
  26452. this.textures.push(newTexture);
  26453. };
  26454. /**
  26455. * Switch active camera
  26456. * @param newCamera defines the new active camera
  26457. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26458. */
  26459. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26460. if (attachControl === void 0) { attachControl = true; }
  26461. var canvas = this._engine.getRenderingCanvas();
  26462. if (!canvas) {
  26463. return;
  26464. }
  26465. if (this.activeCamera) {
  26466. this.activeCamera.detachControl(canvas);
  26467. }
  26468. this.activeCamera = newCamera;
  26469. if (attachControl) {
  26470. newCamera.attachControl(canvas);
  26471. }
  26472. };
  26473. /**
  26474. * sets the active camera of the scene using its ID
  26475. * @param id defines the camera's ID
  26476. * @return the new active camera or null if none found.
  26477. */
  26478. Scene.prototype.setActiveCameraByID = function (id) {
  26479. var camera = this.getCameraByID(id);
  26480. if (camera) {
  26481. this.activeCamera = camera;
  26482. return camera;
  26483. }
  26484. return null;
  26485. };
  26486. /**
  26487. * sets the active camera of the scene using its name
  26488. * @param name defines the camera's name
  26489. * @returns the new active camera or null if none found.
  26490. */
  26491. Scene.prototype.setActiveCameraByName = function (name) {
  26492. var camera = this.getCameraByName(name);
  26493. if (camera) {
  26494. this.activeCamera = camera;
  26495. return camera;
  26496. }
  26497. return null;
  26498. };
  26499. /**
  26500. * get an animation group using its name
  26501. * @param name defines the material's name
  26502. * @return the animation group or null if none found.
  26503. */
  26504. Scene.prototype.getAnimationGroupByName = function (name) {
  26505. for (var index = 0; index < this.animationGroups.length; index++) {
  26506. if (this.animationGroups[index].name === name) {
  26507. return this.animationGroups[index];
  26508. }
  26509. }
  26510. return null;
  26511. };
  26512. /**
  26513. * get a material using its id
  26514. * @param id defines the material's ID
  26515. * @return the material or null if none found.
  26516. */
  26517. Scene.prototype.getMaterialByID = function (id) {
  26518. for (var index = 0; index < this.materials.length; index++) {
  26519. if (this.materials[index].id === id) {
  26520. return this.materials[index];
  26521. }
  26522. }
  26523. return null;
  26524. };
  26525. /**
  26526. * Gets a material using its name
  26527. * @param name defines the material's name
  26528. * @return the material or null if none found.
  26529. */
  26530. Scene.prototype.getMaterialByName = function (name) {
  26531. for (var index = 0; index < this.materials.length; index++) {
  26532. if (this.materials[index].name === name) {
  26533. return this.materials[index];
  26534. }
  26535. }
  26536. return null;
  26537. };
  26538. /**
  26539. * Gets a lens flare system using its name
  26540. * @param name defines the name to look for
  26541. * @returns the lens flare system or null if not found
  26542. */
  26543. Scene.prototype.getLensFlareSystemByName = function (name) {
  26544. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26545. if (this.lensFlareSystems[index].name === name) {
  26546. return this.lensFlareSystems[index];
  26547. }
  26548. }
  26549. return null;
  26550. };
  26551. /**
  26552. * Gets a lens flare system using its id
  26553. * @param id defines the id to look for
  26554. * @returns the lens flare system or null if not found
  26555. */
  26556. Scene.prototype.getLensFlareSystemByID = function (id) {
  26557. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26558. if (this.lensFlareSystems[index].id === id) {
  26559. return this.lensFlareSystems[index];
  26560. }
  26561. }
  26562. return null;
  26563. };
  26564. /**
  26565. * Gets a camera using its id
  26566. * @param id defines the id to look for
  26567. * @returns the camera or null if not found
  26568. */
  26569. Scene.prototype.getCameraByID = function (id) {
  26570. for (var index = 0; index < this.cameras.length; index++) {
  26571. if (this.cameras[index].id === id) {
  26572. return this.cameras[index];
  26573. }
  26574. }
  26575. return null;
  26576. };
  26577. /**
  26578. * Gets a camera using its unique id
  26579. * @param uniqueId defines the unique id to look for
  26580. * @returns the camera or null if not found
  26581. */
  26582. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26583. for (var index = 0; index < this.cameras.length; index++) {
  26584. if (this.cameras[index].uniqueId === uniqueId) {
  26585. return this.cameras[index];
  26586. }
  26587. }
  26588. return null;
  26589. };
  26590. /**
  26591. * Gets a camera using its name
  26592. * @param name defines the camera's name
  26593. * @return the camera or null if none found.
  26594. */
  26595. Scene.prototype.getCameraByName = function (name) {
  26596. for (var index = 0; index < this.cameras.length; index++) {
  26597. if (this.cameras[index].name === name) {
  26598. return this.cameras[index];
  26599. }
  26600. }
  26601. return null;
  26602. };
  26603. /**
  26604. * Gets a bone using its id
  26605. * @param id defines the bone's id
  26606. * @return the bone or null if not found
  26607. */
  26608. Scene.prototype.getBoneByID = function (id) {
  26609. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26610. var skeleton = this.skeletons[skeletonIndex];
  26611. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26612. if (skeleton.bones[boneIndex].id === id) {
  26613. return skeleton.bones[boneIndex];
  26614. }
  26615. }
  26616. }
  26617. return null;
  26618. };
  26619. /**
  26620. * Gets a bone using its id
  26621. * @param name defines the bone's name
  26622. * @return the bone or null if not found
  26623. */
  26624. Scene.prototype.getBoneByName = function (name) {
  26625. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26626. var skeleton = this.skeletons[skeletonIndex];
  26627. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26628. if (skeleton.bones[boneIndex].name === name) {
  26629. return skeleton.bones[boneIndex];
  26630. }
  26631. }
  26632. }
  26633. return null;
  26634. };
  26635. /**
  26636. * Gets a light node using its name
  26637. * @param name defines the the light's name
  26638. * @return the light or null if none found.
  26639. */
  26640. Scene.prototype.getLightByName = function (name) {
  26641. for (var index = 0; index < this.lights.length; index++) {
  26642. if (this.lights[index].name === name) {
  26643. return this.lights[index];
  26644. }
  26645. }
  26646. return null;
  26647. };
  26648. /**
  26649. * Gets a light node using its id
  26650. * @param id defines the light's id
  26651. * @return the light or null if none found.
  26652. */
  26653. Scene.prototype.getLightByID = function (id) {
  26654. for (var index = 0; index < this.lights.length; index++) {
  26655. if (this.lights[index].id === id) {
  26656. return this.lights[index];
  26657. }
  26658. }
  26659. return null;
  26660. };
  26661. /**
  26662. * Gets a light node using its scene-generated unique ID
  26663. * @param uniqueId defines the light's unique id
  26664. * @return the light or null if none found.
  26665. */
  26666. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26667. for (var index = 0; index < this.lights.length; index++) {
  26668. if (this.lights[index].uniqueId === uniqueId) {
  26669. return this.lights[index];
  26670. }
  26671. }
  26672. return null;
  26673. };
  26674. /**
  26675. * Gets a particle system by id
  26676. * @param id defines the particle system id
  26677. * @return the corresponding system or null if none found
  26678. */
  26679. Scene.prototype.getParticleSystemByID = function (id) {
  26680. for (var index = 0; index < this.particleSystems.length; index++) {
  26681. if (this.particleSystems[index].id === id) {
  26682. return this.particleSystems[index];
  26683. }
  26684. }
  26685. return null;
  26686. };
  26687. /**
  26688. * Gets a geometry using its ID
  26689. * @param id defines the geometry's id
  26690. * @return the geometry or null if none found.
  26691. */
  26692. Scene.prototype.getGeometryByID = function (id) {
  26693. for (var index = 0; index < this._geometries.length; index++) {
  26694. if (this._geometries[index].id === id) {
  26695. return this._geometries[index];
  26696. }
  26697. }
  26698. return null;
  26699. };
  26700. /**
  26701. * Add a new geometry to this scene
  26702. * @param geometry defines the geometry to be added to the scene.
  26703. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26704. * @return a boolean defining if the geometry was added or not
  26705. */
  26706. Scene.prototype.pushGeometry = function (geometry, force) {
  26707. if (!force && this.getGeometryByID(geometry.id)) {
  26708. return false;
  26709. }
  26710. this._geometries.push(geometry);
  26711. //notify the collision coordinator
  26712. if (this.collisionCoordinator) {
  26713. this.collisionCoordinator.onGeometryAdded(geometry);
  26714. }
  26715. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26716. return true;
  26717. };
  26718. /**
  26719. * Removes an existing geometry
  26720. * @param geometry defines the geometry to be removed from the scene
  26721. * @return a boolean defining if the geometry was removed or not
  26722. */
  26723. Scene.prototype.removeGeometry = function (geometry) {
  26724. var index = this._geometries.indexOf(geometry);
  26725. if (index > -1) {
  26726. this._geometries.splice(index, 1);
  26727. //notify the collision coordinator
  26728. if (this.collisionCoordinator) {
  26729. this.collisionCoordinator.onGeometryDeleted(geometry);
  26730. }
  26731. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26732. return true;
  26733. }
  26734. return false;
  26735. };
  26736. /**
  26737. * Gets the list of geometries attached to the scene
  26738. * @returns an array of Geometry
  26739. */
  26740. Scene.prototype.getGeometries = function () {
  26741. return this._geometries;
  26742. };
  26743. /**
  26744. * Gets the first added mesh found of a given ID
  26745. * @param id defines the id to search for
  26746. * @return the mesh found or null if not found at all
  26747. */
  26748. Scene.prototype.getMeshByID = function (id) {
  26749. for (var index = 0; index < this.meshes.length; index++) {
  26750. if (this.meshes[index].id === id) {
  26751. return this.meshes[index];
  26752. }
  26753. }
  26754. return null;
  26755. };
  26756. /**
  26757. * Gets a list of meshes using their id
  26758. * @param id defines the id to search for
  26759. * @returns a list of meshes
  26760. */
  26761. Scene.prototype.getMeshesByID = function (id) {
  26762. return this.meshes.filter(function (m) {
  26763. return m.id === id;
  26764. });
  26765. };
  26766. /**
  26767. * Gets the first added transform node found of a given ID
  26768. * @param id defines the id to search for
  26769. * @return the found transform node or null if not found at all.
  26770. */
  26771. Scene.prototype.getTransformNodeByID = function (id) {
  26772. for (var index = 0; index < this.transformNodes.length; index++) {
  26773. if (this.transformNodes[index].id === id) {
  26774. return this.transformNodes[index];
  26775. }
  26776. }
  26777. return null;
  26778. };
  26779. /**
  26780. * Gets a list of transform nodes using their id
  26781. * @param id defines the id to search for
  26782. * @returns a list of transform nodes
  26783. */
  26784. Scene.prototype.getTransformNodesByID = function (id) {
  26785. return this.transformNodes.filter(function (m) {
  26786. return m.id === id;
  26787. });
  26788. };
  26789. /**
  26790. * Gets a mesh with its auto-generated unique id
  26791. * @param uniqueId defines the unique id to search for
  26792. * @return the found mesh or null if not found at all.
  26793. */
  26794. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26795. for (var index = 0; index < this.meshes.length; index++) {
  26796. if (this.meshes[index].uniqueId === uniqueId) {
  26797. return this.meshes[index];
  26798. }
  26799. }
  26800. return null;
  26801. };
  26802. /**
  26803. * Gets a the last added mesh using a given id
  26804. * @param id defines the id to search for
  26805. * @return the found mesh or null if not found at all.
  26806. */
  26807. Scene.prototype.getLastMeshByID = function (id) {
  26808. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26809. if (this.meshes[index].id === id) {
  26810. return this.meshes[index];
  26811. }
  26812. }
  26813. return null;
  26814. };
  26815. /**
  26816. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26817. * @param id defines the id to search for
  26818. * @return the found node or null if not found at all
  26819. */
  26820. Scene.prototype.getLastEntryByID = function (id) {
  26821. var index;
  26822. for (index = this.meshes.length - 1; index >= 0; index--) {
  26823. if (this.meshes[index].id === id) {
  26824. return this.meshes[index];
  26825. }
  26826. }
  26827. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26828. if (this.transformNodes[index].id === id) {
  26829. return this.transformNodes[index];
  26830. }
  26831. }
  26832. for (index = this.cameras.length - 1; index >= 0; index--) {
  26833. if (this.cameras[index].id === id) {
  26834. return this.cameras[index];
  26835. }
  26836. }
  26837. for (index = this.lights.length - 1; index >= 0; index--) {
  26838. if (this.lights[index].id === id) {
  26839. return this.lights[index];
  26840. }
  26841. }
  26842. return null;
  26843. };
  26844. /**
  26845. * Gets a node (Mesh, Camera, Light) using a given id
  26846. * @param id defines the id to search for
  26847. * @return the found node or null if not found at all
  26848. */
  26849. Scene.prototype.getNodeByID = function (id) {
  26850. var mesh = this.getMeshByID(id);
  26851. if (mesh) {
  26852. return mesh;
  26853. }
  26854. var light = this.getLightByID(id);
  26855. if (light) {
  26856. return light;
  26857. }
  26858. var camera = this.getCameraByID(id);
  26859. if (camera) {
  26860. return camera;
  26861. }
  26862. var bone = this.getBoneByID(id);
  26863. return bone;
  26864. };
  26865. /**
  26866. * Gets a node (Mesh, Camera, Light) using a given name
  26867. * @param name defines the name to search for
  26868. * @return the found node or null if not found at all.
  26869. */
  26870. Scene.prototype.getNodeByName = function (name) {
  26871. var mesh = this.getMeshByName(name);
  26872. if (mesh) {
  26873. return mesh;
  26874. }
  26875. var light = this.getLightByName(name);
  26876. if (light) {
  26877. return light;
  26878. }
  26879. var camera = this.getCameraByName(name);
  26880. if (camera) {
  26881. return camera;
  26882. }
  26883. var bone = this.getBoneByName(name);
  26884. return bone;
  26885. };
  26886. /**
  26887. * Gets a mesh using a given name
  26888. * @param name defines the name to search for
  26889. * @return the found mesh or null if not found at all.
  26890. */
  26891. Scene.prototype.getMeshByName = function (name) {
  26892. for (var index = 0; index < this.meshes.length; index++) {
  26893. if (this.meshes[index].name === name) {
  26894. return this.meshes[index];
  26895. }
  26896. }
  26897. return null;
  26898. };
  26899. /**
  26900. * Gets a transform node using a given name
  26901. * @param name defines the name to search for
  26902. * @return the found transform node or null if not found at all.
  26903. */
  26904. Scene.prototype.getTransformNodeByName = function (name) {
  26905. for (var index = 0; index < this.transformNodes.length; index++) {
  26906. if (this.transformNodes[index].name === name) {
  26907. return this.transformNodes[index];
  26908. }
  26909. }
  26910. return null;
  26911. };
  26912. /**
  26913. * Gets a sound using a given name
  26914. * @param name defines the name to search for
  26915. * @return the found sound or null if not found at all.
  26916. */
  26917. Scene.prototype.getSoundByName = function (name) {
  26918. var index;
  26919. if (BABYLON.AudioEngine) {
  26920. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26921. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26922. return this.mainSoundTrack.soundCollection[index];
  26923. }
  26924. }
  26925. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26926. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26927. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26928. return this.soundTracks[sdIndex].soundCollection[index];
  26929. }
  26930. }
  26931. }
  26932. }
  26933. return null;
  26934. };
  26935. /**
  26936. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26937. * @param id defines the id to search for
  26938. * @return the found skeleton or null if not found at all.
  26939. */
  26940. Scene.prototype.getLastSkeletonByID = function (id) {
  26941. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26942. if (this.skeletons[index].id === id) {
  26943. return this.skeletons[index];
  26944. }
  26945. }
  26946. return null;
  26947. };
  26948. /**
  26949. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26950. * @param id defines the id to search for
  26951. * @return the found skeleton or null if not found at all.
  26952. */
  26953. Scene.prototype.getSkeletonById = function (id) {
  26954. for (var index = 0; index < this.skeletons.length; index++) {
  26955. if (this.skeletons[index].id === id) {
  26956. return this.skeletons[index];
  26957. }
  26958. }
  26959. return null;
  26960. };
  26961. /**
  26962. * Gets a skeleton using a given name
  26963. * @param name defines the name to search for
  26964. * @return the found skeleton or null if not found at all.
  26965. */
  26966. Scene.prototype.getSkeletonByName = function (name) {
  26967. for (var index = 0; index < this.skeletons.length; index++) {
  26968. if (this.skeletons[index].name === name) {
  26969. return this.skeletons[index];
  26970. }
  26971. }
  26972. return null;
  26973. };
  26974. /**
  26975. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26976. * @param id defines the id to search for
  26977. * @return the found morph target manager or null if not found at all.
  26978. */
  26979. Scene.prototype.getMorphTargetManagerById = function (id) {
  26980. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26981. if (this.morphTargetManagers[index].uniqueId === id) {
  26982. return this.morphTargetManagers[index];
  26983. }
  26984. }
  26985. return null;
  26986. };
  26987. /**
  26988. * Gets a boolean indicating if the given mesh is active
  26989. * @param mesh defines the mesh to look for
  26990. * @returns true if the mesh is in the active list
  26991. */
  26992. Scene.prototype.isActiveMesh = function (mesh) {
  26993. return (this._activeMeshes.indexOf(mesh) !== -1);
  26994. };
  26995. /**
  26996. * Return a the first highlight layer of the scene with a given name.
  26997. * @param name The name of the highlight layer to look for.
  26998. * @return The highlight layer if found otherwise null.
  26999. */
  27000. Scene.prototype.getHighlightLayerByName = function (name) {
  27001. for (var index = 0; index < this.effectLayers.length; index++) {
  27002. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27003. return this.effectLayers[index];
  27004. }
  27005. }
  27006. return null;
  27007. };
  27008. /**
  27009. * Return a the first highlight layer of the scene with a given name.
  27010. * @param name The name of the highlight layer to look for.
  27011. * @return The highlight layer if found otherwise null.
  27012. */
  27013. Scene.prototype.getGlowLayerByName = function (name) {
  27014. for (var index = 0; index < this.effectLayers.length; index++) {
  27015. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27016. return this.effectLayers[index];
  27017. }
  27018. }
  27019. return null;
  27020. };
  27021. Object.defineProperty(Scene.prototype, "uid", {
  27022. /**
  27023. * Return a unique id as a string which can serve as an identifier for the scene
  27024. */
  27025. get: function () {
  27026. if (!this._uid) {
  27027. this._uid = BABYLON.Tools.RandomId();
  27028. }
  27029. return this._uid;
  27030. },
  27031. enumerable: true,
  27032. configurable: true
  27033. });
  27034. /**
  27035. * Add an externaly attached data from its key.
  27036. * This method call will fail and return false, if such key already exists.
  27037. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27038. * @param key the unique key that identifies the data
  27039. * @param data the data object to associate to the key for this Engine instance
  27040. * @return true if no such key were already present and the data was added successfully, false otherwise
  27041. */
  27042. Scene.prototype.addExternalData = function (key, data) {
  27043. if (!this._externalData) {
  27044. this._externalData = new BABYLON.StringDictionary();
  27045. }
  27046. return this._externalData.add(key, data);
  27047. };
  27048. /**
  27049. * Get an externaly attached data from its key
  27050. * @param key the unique key that identifies the data
  27051. * @return the associated data, if present (can be null), or undefined if not present
  27052. */
  27053. Scene.prototype.getExternalData = function (key) {
  27054. if (!this._externalData) {
  27055. return null;
  27056. }
  27057. return this._externalData.get(key);
  27058. };
  27059. /**
  27060. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27061. * @param key the unique key that identifies the data
  27062. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27063. * @return the associated data, can be null if the factory returned null.
  27064. */
  27065. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27066. if (!this._externalData) {
  27067. this._externalData = new BABYLON.StringDictionary();
  27068. }
  27069. return this._externalData.getOrAddWithFactory(key, factory);
  27070. };
  27071. /**
  27072. * Remove an externaly attached data from the Engine instance
  27073. * @param key the unique key that identifies the data
  27074. * @return true if the data was successfully removed, false if it doesn't exist
  27075. */
  27076. Scene.prototype.removeExternalData = function (key) {
  27077. return this._externalData.remove(key);
  27078. };
  27079. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27080. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27081. if (mesh.showSubMeshesBoundingBox) {
  27082. var boundingInfo = subMesh.getBoundingInfo();
  27083. if (boundingInfo !== null && boundingInfo !== undefined) {
  27084. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27085. }
  27086. }
  27087. var material = subMesh.getMaterial();
  27088. if (material !== null && material !== undefined) {
  27089. // Render targets
  27090. if (material.getRenderTargetTextures !== undefined) {
  27091. if (this._processedMaterials.indexOf(material) === -1) {
  27092. this._processedMaterials.push(material);
  27093. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27094. }
  27095. }
  27096. // Dispatch
  27097. this._activeIndices.addCount(subMesh.indexCount, false);
  27098. this._renderingManager.dispatch(subMesh, mesh, material);
  27099. }
  27100. }
  27101. };
  27102. /**
  27103. * Clear the processed materials smart array preventing retention point in material dispose.
  27104. */
  27105. Scene.prototype.freeProcessedMaterials = function () {
  27106. this._processedMaterials.dispose();
  27107. };
  27108. /**
  27109. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27110. */
  27111. Scene.prototype.freeActiveMeshes = function () {
  27112. this._activeMeshes.dispose();
  27113. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27114. this.activeCamera._activeMeshes.dispose();
  27115. }
  27116. if (this.activeCameras) {
  27117. for (var i = 0; i < this.activeCameras.length; i++) {
  27118. var activeCamera = this.activeCameras[i];
  27119. if (activeCamera && activeCamera._activeMeshes) {
  27120. activeCamera._activeMeshes.dispose();
  27121. }
  27122. }
  27123. }
  27124. };
  27125. /**
  27126. * Clear the info related to rendering groups preventing retention points during dispose.
  27127. */
  27128. Scene.prototype.freeRenderingGroups = function () {
  27129. if (this._renderingManager) {
  27130. this._renderingManager.freeRenderingGroups();
  27131. }
  27132. if (this.textures) {
  27133. for (var i = 0; i < this.textures.length; i++) {
  27134. var texture = this.textures[i];
  27135. if (texture && texture.renderList) {
  27136. texture.freeRenderingGroups();
  27137. }
  27138. }
  27139. }
  27140. };
  27141. /** @hidden */
  27142. Scene.prototype._isInIntermediateRendering = function () {
  27143. return this._intermediateRendering;
  27144. };
  27145. /**
  27146. * Defines the current active mesh candidate provider
  27147. * @param provider defines the provider to use
  27148. */
  27149. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27150. this._activeMeshCandidateProvider = provider;
  27151. };
  27152. /**
  27153. * Gets the current active mesh candidate provider
  27154. * @returns the current active mesh candidate provider
  27155. */
  27156. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27157. return this._activeMeshCandidateProvider;
  27158. };
  27159. /**
  27160. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27161. * @returns the current scene
  27162. */
  27163. Scene.prototype.freezeActiveMeshes = function () {
  27164. if (!this.activeCamera) {
  27165. return this;
  27166. }
  27167. if (!this._frustumPlanes) {
  27168. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27169. }
  27170. this._evaluateActiveMeshes();
  27171. this._activeMeshesFrozen = true;
  27172. return this;
  27173. };
  27174. /**
  27175. * Use this function to restart evaluating active meshes on every frame
  27176. * @returns the current scene
  27177. */
  27178. Scene.prototype.unfreezeActiveMeshes = function () {
  27179. this._activeMeshesFrozen = false;
  27180. return this;
  27181. };
  27182. Scene.prototype._evaluateActiveMeshes = function () {
  27183. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27184. return;
  27185. }
  27186. if (!this.activeCamera) {
  27187. return;
  27188. }
  27189. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27190. this.activeCamera._activeMeshes.reset();
  27191. this._activeMeshes.reset();
  27192. this._renderingManager.reset();
  27193. this._processedMaterials.reset();
  27194. this._activeParticleSystems.reset();
  27195. this._activeSkeletons.reset();
  27196. this._softwareSkinnedMeshes.reset();
  27197. if (this._boundingBoxRenderer) {
  27198. this._boundingBoxRenderer.reset();
  27199. }
  27200. // Meshes
  27201. var meshes;
  27202. var len;
  27203. var checkIsEnabled = true;
  27204. // Determine mesh candidates
  27205. if (this._activeMeshCandidateProvider !== undefined) {
  27206. // Use _activeMeshCandidateProvider
  27207. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27208. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27209. if (meshes !== undefined) {
  27210. len = meshes.length;
  27211. }
  27212. else {
  27213. len = 0;
  27214. }
  27215. }
  27216. else if (this._selectionOctree !== undefined) {
  27217. // Octree
  27218. var selection = this._selectionOctree.select(this._frustumPlanes);
  27219. meshes = selection.data;
  27220. len = selection.length;
  27221. }
  27222. else {
  27223. // Full scene traversal
  27224. len = this.meshes.length;
  27225. meshes = this.meshes;
  27226. }
  27227. // Check each mesh
  27228. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27229. mesh = meshes[meshIndex];
  27230. if (mesh.isBlocked) {
  27231. continue;
  27232. }
  27233. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27234. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27235. continue;
  27236. }
  27237. mesh.computeWorldMatrix();
  27238. // Intersections
  27239. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27240. this._meshesForIntersections.pushNoDuplicate(mesh);
  27241. }
  27242. // Switch to current LOD
  27243. meshLOD = mesh.getLOD(this.activeCamera);
  27244. if (meshLOD === undefined || meshLOD === null) {
  27245. continue;
  27246. }
  27247. mesh._preActivate();
  27248. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27249. this._activeMeshes.push(mesh);
  27250. this.activeCamera._activeMeshes.push(mesh);
  27251. mesh._activate(this._renderId);
  27252. if (meshLOD !== mesh) {
  27253. meshLOD._activate(this._renderId);
  27254. }
  27255. this._activeMesh(mesh, meshLOD);
  27256. }
  27257. }
  27258. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27259. // Particle systems
  27260. if (this.particlesEnabled) {
  27261. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27262. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27263. var particleSystem = this.particleSystems[particleIndex];
  27264. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27265. continue;
  27266. }
  27267. var emitter = particleSystem.emitter;
  27268. if (!emitter.position || emitter.isEnabled()) {
  27269. this._activeParticleSystems.push(particleSystem);
  27270. particleSystem.animate();
  27271. this._renderingManager.dispatchParticles(particleSystem);
  27272. }
  27273. }
  27274. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27275. }
  27276. };
  27277. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27278. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27279. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27280. mesh.skeleton.prepare();
  27281. }
  27282. if (!mesh.computeBonesUsingShaders) {
  27283. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27284. }
  27285. }
  27286. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27287. var boundingInfo = sourceMesh.getBoundingInfo();
  27288. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27289. }
  27290. if (mesh !== undefined && mesh !== null
  27291. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27292. // Submeshes Octrees
  27293. var len;
  27294. var subMeshes;
  27295. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27296. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27297. len = intersections.length;
  27298. subMeshes = intersections.data;
  27299. }
  27300. else {
  27301. subMeshes = mesh.subMeshes;
  27302. len = subMeshes.length;
  27303. }
  27304. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27305. subMesh = subMeshes[subIndex];
  27306. this._evaluateSubMesh(subMesh, mesh);
  27307. }
  27308. }
  27309. };
  27310. /**
  27311. * Update the transform matrix to update from the current active camera
  27312. * @param force defines a boolean used to force the update even if cache is up to date
  27313. */
  27314. Scene.prototype.updateTransformMatrix = function (force) {
  27315. if (!this.activeCamera) {
  27316. return;
  27317. }
  27318. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27319. };
  27320. /**
  27321. * 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)
  27322. * @param alternateCamera defines the camera to use
  27323. */
  27324. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27325. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27326. };
  27327. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27328. if (camera && camera._skipRendering) {
  27329. return;
  27330. }
  27331. var engine = this._engine;
  27332. this.activeCamera = camera;
  27333. if (!this.activeCamera)
  27334. throw new Error("Active camera not set");
  27335. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27336. // Viewport
  27337. engine.setViewport(this.activeCamera.viewport);
  27338. // Camera
  27339. this.resetCachedMaterial();
  27340. this._renderId++;
  27341. this.updateTransformMatrix();
  27342. if (camera._alternateCamera) {
  27343. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27344. this._alternateRendering = true;
  27345. }
  27346. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27347. // Meshes
  27348. this._evaluateActiveMeshes();
  27349. // Software skinning
  27350. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27351. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27352. mesh.applySkeleton(mesh.skeleton);
  27353. }
  27354. // Render targets
  27355. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27356. var needsRestoreFrameBuffer = false;
  27357. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27358. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27359. }
  27360. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27361. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27362. }
  27363. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27364. this._intermediateRendering = true;
  27365. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27366. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27367. var renderTarget = this._renderTargets.data[renderIndex];
  27368. if (renderTarget._shouldRender()) {
  27369. this._renderId++;
  27370. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27371. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27372. }
  27373. }
  27374. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27375. this._intermediateRendering = false;
  27376. this._renderId++;
  27377. needsRestoreFrameBuffer = true; // Restore back buffer
  27378. }
  27379. // Render EffecttLayer Texture
  27380. var stencilState = this._engine.getStencilBuffer();
  27381. var renderEffects = false;
  27382. var needStencil = false;
  27383. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27384. this._intermediateRendering = true;
  27385. for (var i = 0; i < this.effectLayers.length; i++) {
  27386. var effectLayer = this.effectLayers[i];
  27387. if (effectLayer.shouldRender() &&
  27388. (!effectLayer.camera ||
  27389. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27390. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27391. renderEffects = true;
  27392. needStencil = needStencil || effectLayer.needStencil();
  27393. var renderTarget = effectLayer._mainTexture;
  27394. if (renderTarget._shouldRender()) {
  27395. this._renderId++;
  27396. renderTarget.render(false, false);
  27397. needsRestoreFrameBuffer = true;
  27398. }
  27399. }
  27400. }
  27401. this._intermediateRendering = false;
  27402. this._renderId++;
  27403. }
  27404. if (needsRestoreFrameBuffer) {
  27405. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27406. }
  27407. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27408. // Prepare Frame
  27409. this.postProcessManager._prepareFrame();
  27410. // Backgrounds
  27411. var layerIndex;
  27412. var layer;
  27413. if (this.layers.length) {
  27414. engine.setDepthBuffer(false);
  27415. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27416. layer = this.layers[layerIndex];
  27417. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27418. layer.render();
  27419. }
  27420. }
  27421. engine.setDepthBuffer(true);
  27422. }
  27423. // Activate effect Layer stencil
  27424. if (needStencil) {
  27425. this._engine.setStencilBuffer(true);
  27426. }
  27427. // Render
  27428. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27429. this._renderingManager.render(null, null, true, true);
  27430. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27431. // Restore effect Layer stencil
  27432. if (needStencil) {
  27433. this._engine.setStencilBuffer(stencilState);
  27434. }
  27435. // Bounding boxes
  27436. if (this._boundingBoxRenderer) {
  27437. this._boundingBoxRenderer.render();
  27438. }
  27439. // Lens flares
  27440. if (this.lensFlaresEnabled) {
  27441. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27442. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27443. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27444. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27445. lensFlareSystem.render();
  27446. }
  27447. }
  27448. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27449. }
  27450. // Effect Layer
  27451. if (renderEffects) {
  27452. engine.setDepthBuffer(false);
  27453. for (var i = 0; i < this.effectLayers.length; i++) {
  27454. if (this.effectLayers[i].shouldRender()) {
  27455. this.effectLayers[i].render();
  27456. }
  27457. }
  27458. engine.setDepthBuffer(true);
  27459. }
  27460. // Foregrounds
  27461. if (this.layers.length) {
  27462. engine.setDepthBuffer(false);
  27463. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27464. layer = this.layers[layerIndex];
  27465. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27466. layer.render();
  27467. }
  27468. }
  27469. engine.setDepthBuffer(true);
  27470. }
  27471. // Finalize frame
  27472. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27473. // Reset some special arrays
  27474. this._renderTargets.reset();
  27475. this._alternateRendering = false;
  27476. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27477. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27478. };
  27479. Scene.prototype._processSubCameras = function (camera) {
  27480. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27481. this._renderForCamera(camera);
  27482. return;
  27483. }
  27484. // rig cameras
  27485. for (var index = 0; index < camera._rigCameras.length; index++) {
  27486. this._renderForCamera(camera._rigCameras[index], camera);
  27487. }
  27488. this.activeCamera = camera;
  27489. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27490. };
  27491. Scene.prototype._checkIntersections = function () {
  27492. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27493. var sourceMesh = this._meshesForIntersections.data[index];
  27494. if (!sourceMesh.actionManager) {
  27495. continue;
  27496. }
  27497. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27498. var action = sourceMesh.actionManager.actions[actionIndex];
  27499. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27500. var parameters = action.getTriggerParameter();
  27501. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27502. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27503. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27504. if (areIntersecting && currentIntersectionInProgress === -1) {
  27505. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27506. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27507. sourceMesh._intersectionsInProgress.push(otherMesh);
  27508. }
  27509. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27510. sourceMesh._intersectionsInProgress.push(otherMesh);
  27511. }
  27512. }
  27513. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27514. //They intersected, and now they don't.
  27515. //is this trigger an exit trigger? execute an event.
  27516. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27517. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27518. }
  27519. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27520. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27521. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27522. return otherMesh === parameterMesh;
  27523. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27524. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27525. }
  27526. }
  27527. }
  27528. }
  27529. }
  27530. };
  27531. /**
  27532. * Render the scene
  27533. */
  27534. Scene.prototype.render = function () {
  27535. if (this.isDisposed) {
  27536. return;
  27537. }
  27538. this._activeParticles.fetchNewFrame();
  27539. this._totalVertices.fetchNewFrame();
  27540. this._activeIndices.fetchNewFrame();
  27541. this._activeBones.fetchNewFrame();
  27542. this._meshesForIntersections.reset();
  27543. this.resetCachedMaterial();
  27544. this.onBeforeAnimationsObservable.notifyObservers(this);
  27545. // Actions
  27546. if (this.actionManager) {
  27547. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27548. }
  27549. //Simplification Queue
  27550. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27551. this.simplificationQueue.executeNext();
  27552. }
  27553. if (this._engine.isDeterministicLockStep()) {
  27554. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27555. var defaultFPS = (60.0 / 1000.0);
  27556. var defaultFrameTime = 1000 / 60; // frame time in MS
  27557. if (this._physicsEngine) {
  27558. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27559. }
  27560. var stepsTaken = 0;
  27561. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27562. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27563. internalSteps = Math.min(internalSteps, maxSubSteps);
  27564. do {
  27565. this.onBeforeStepObservable.notifyObservers(this);
  27566. // Animations
  27567. this._animationRatio = defaultFrameTime * defaultFPS;
  27568. this._animate();
  27569. this.onAfterAnimationsObservable.notifyObservers(this);
  27570. // Physics
  27571. if (this._physicsEngine) {
  27572. this.onBeforePhysicsObservable.notifyObservers(this);
  27573. this._physicsEngine._step(defaultFrameTime / 1000);
  27574. this.onAfterPhysicsObservable.notifyObservers(this);
  27575. }
  27576. this.onAfterStepObservable.notifyObservers(this);
  27577. this._currentStepId++;
  27578. stepsTaken++;
  27579. deltaTime -= defaultFrameTime;
  27580. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27581. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27582. }
  27583. else {
  27584. // Animations
  27585. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27586. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27587. this._animate();
  27588. this.onAfterAnimationsObservable.notifyObservers(this);
  27589. // Physics
  27590. if (this._physicsEngine) {
  27591. this.onBeforePhysicsObservable.notifyObservers(this);
  27592. this._physicsEngine._step(deltaTime / 1000.0);
  27593. this.onAfterPhysicsObservable.notifyObservers(this);
  27594. }
  27595. }
  27596. // update gamepad manager
  27597. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27598. this._gamepadManager._checkGamepadsStatus();
  27599. }
  27600. // Update Cameras
  27601. if (this.activeCameras.length > 0) {
  27602. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27603. var camera = this.activeCameras[cameraIndex];
  27604. camera.update();
  27605. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27606. // rig cameras
  27607. for (var index = 0; index < camera._rigCameras.length; index++) {
  27608. camera._rigCameras[index].update();
  27609. }
  27610. }
  27611. }
  27612. }
  27613. else if (this.activeCamera) {
  27614. this.activeCamera.update();
  27615. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27616. // rig cameras
  27617. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27618. this.activeCamera._rigCameras[index].update();
  27619. }
  27620. }
  27621. }
  27622. // Before render
  27623. this.onBeforeRenderObservable.notifyObservers(this);
  27624. // Customs render targets
  27625. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27626. var engine = this.getEngine();
  27627. var currentActiveCamera = this.activeCamera;
  27628. if (this.renderTargetsEnabled) {
  27629. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27630. this._intermediateRendering = true;
  27631. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27632. var renderTarget = this.customRenderTargets[customIndex];
  27633. if (renderTarget._shouldRender()) {
  27634. this._renderId++;
  27635. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27636. if (!this.activeCamera)
  27637. throw new Error("Active camera not set");
  27638. // Viewport
  27639. engine.setViewport(this.activeCamera.viewport);
  27640. // Camera
  27641. this.updateTransformMatrix();
  27642. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27643. }
  27644. }
  27645. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27646. this._intermediateRendering = false;
  27647. this._renderId++;
  27648. }
  27649. // Restore back buffer
  27650. if (this.customRenderTargets.length > 0) {
  27651. engine.restoreDefaultFramebuffer();
  27652. }
  27653. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27654. this.activeCamera = currentActiveCamera;
  27655. // Procedural textures
  27656. if (this.proceduralTexturesEnabled) {
  27657. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27658. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27659. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27660. if (proceduralTexture._shouldRender()) {
  27661. proceduralTexture.render();
  27662. }
  27663. }
  27664. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27665. }
  27666. // Clear
  27667. if (this.autoClearDepthAndStencil || this.autoClear) {
  27668. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27669. }
  27670. // Shadows
  27671. if (this.shadowsEnabled) {
  27672. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27673. var light = this.lights[lightIndex];
  27674. var shadowGenerator = light.getShadowGenerator();
  27675. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27676. var shadowMap = (shadowGenerator.getShadowMap());
  27677. if (this.textures.indexOf(shadowMap) !== -1) {
  27678. this._renderTargets.push(shadowMap);
  27679. }
  27680. }
  27681. }
  27682. }
  27683. // Depth renderer
  27684. for (var key in this._depthRenderer) {
  27685. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27686. }
  27687. // Geometry renderer
  27688. if (this._geometryBufferRenderer) {
  27689. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27690. }
  27691. // RenderPipeline
  27692. if (this._postProcessRenderPipelineManager) {
  27693. this._postProcessRenderPipelineManager.update();
  27694. }
  27695. // Multi-cameras?
  27696. if (this.activeCameras.length > 0) {
  27697. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27698. if (cameraIndex > 0) {
  27699. this._engine.clear(null, false, true, true);
  27700. }
  27701. this._processSubCameras(this.activeCameras[cameraIndex]);
  27702. }
  27703. }
  27704. else {
  27705. if (!this.activeCamera) {
  27706. throw new Error("No camera defined");
  27707. }
  27708. this._processSubCameras(this.activeCamera);
  27709. }
  27710. // Intersection checks
  27711. this._checkIntersections();
  27712. // Update the audio listener attached to the camera
  27713. if (BABYLON.AudioEngine) {
  27714. this._updateAudioParameters();
  27715. }
  27716. // After render
  27717. if (this.afterRender) {
  27718. this.afterRender();
  27719. }
  27720. this.onAfterRenderObservable.notifyObservers(this);
  27721. // Cleaning
  27722. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27723. var data = this._toBeDisposed.data[index];
  27724. if (data) {
  27725. data.dispose();
  27726. }
  27727. this._toBeDisposed[index] = null;
  27728. }
  27729. this._toBeDisposed.reset();
  27730. if (this.dumpNextRenderTargets) {
  27731. this.dumpNextRenderTargets = false;
  27732. }
  27733. this._activeBones.addCount(0, true);
  27734. this._activeIndices.addCount(0, true);
  27735. this._activeParticles.addCount(0, true);
  27736. };
  27737. Scene.prototype._updateAudioParameters = function () {
  27738. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27739. return;
  27740. }
  27741. var listeningCamera;
  27742. var audioEngine = BABYLON.Engine.audioEngine;
  27743. if (this.activeCameras.length > 0) {
  27744. listeningCamera = this.activeCameras[0];
  27745. }
  27746. else {
  27747. listeningCamera = this.activeCamera;
  27748. }
  27749. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27750. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27751. // for VR cameras
  27752. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27753. listeningCamera = listeningCamera.rigCameras[0];
  27754. }
  27755. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27756. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27757. cameraDirection.normalize();
  27758. // To avoid some errors on GearVR
  27759. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27760. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27761. }
  27762. var i;
  27763. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27764. var sound = this.mainSoundTrack.soundCollection[i];
  27765. if (sound.useCustomAttenuation) {
  27766. sound.updateDistanceFromListener();
  27767. }
  27768. }
  27769. for (i = 0; i < this.soundTracks.length; i++) {
  27770. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27771. sound = this.soundTracks[i].soundCollection[j];
  27772. if (sound.useCustomAttenuation) {
  27773. sound.updateDistanceFromListener();
  27774. }
  27775. }
  27776. }
  27777. }
  27778. };
  27779. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27780. // Audio
  27781. /**
  27782. * Gets or sets if audio support is enabled
  27783. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27784. */
  27785. get: function () {
  27786. return this._audioEnabled;
  27787. },
  27788. set: function (value) {
  27789. this._audioEnabled = value;
  27790. if (BABYLON.AudioEngine) {
  27791. if (this._audioEnabled) {
  27792. this._enableAudio();
  27793. }
  27794. else {
  27795. this._disableAudio();
  27796. }
  27797. }
  27798. },
  27799. enumerable: true,
  27800. configurable: true
  27801. });
  27802. Scene.prototype._disableAudio = function () {
  27803. var i;
  27804. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27805. this.mainSoundTrack.soundCollection[i].pause();
  27806. }
  27807. for (i = 0; i < this.soundTracks.length; i++) {
  27808. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27809. this.soundTracks[i].soundCollection[j].pause();
  27810. }
  27811. }
  27812. };
  27813. Scene.prototype._enableAudio = function () {
  27814. var i;
  27815. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27816. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27817. this.mainSoundTrack.soundCollection[i].play();
  27818. }
  27819. }
  27820. for (i = 0; i < this.soundTracks.length; i++) {
  27821. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27822. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27823. this.soundTracks[i].soundCollection[j].play();
  27824. }
  27825. }
  27826. }
  27827. };
  27828. Object.defineProperty(Scene.prototype, "headphone", {
  27829. /**
  27830. * Gets or sets if audio will be output to headphones
  27831. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27832. */
  27833. get: function () {
  27834. return this._headphone;
  27835. },
  27836. set: function (value) {
  27837. this._headphone = value;
  27838. if (BABYLON.AudioEngine) {
  27839. if (this._headphone) {
  27840. this._switchAudioModeForHeadphones();
  27841. }
  27842. else {
  27843. this._switchAudioModeForNormalSpeakers();
  27844. }
  27845. }
  27846. },
  27847. enumerable: true,
  27848. configurable: true
  27849. });
  27850. Scene.prototype._switchAudioModeForHeadphones = function () {
  27851. this.mainSoundTrack.switchPanningModelToHRTF();
  27852. for (var i = 0; i < this.soundTracks.length; i++) {
  27853. this.soundTracks[i].switchPanningModelToHRTF();
  27854. }
  27855. };
  27856. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27857. this.mainSoundTrack.switchPanningModelToEqualPower();
  27858. for (var i = 0; i < this.soundTracks.length; i++) {
  27859. this.soundTracks[i].switchPanningModelToEqualPower();
  27860. }
  27861. };
  27862. /**
  27863. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27864. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27865. * @returns the created depth renderer
  27866. */
  27867. Scene.prototype.enableDepthRenderer = function (camera) {
  27868. camera = camera || this.activeCamera;
  27869. if (!camera) {
  27870. throw "No camera available to enable depth renderer";
  27871. }
  27872. if (!this._depthRenderer[camera.id]) {
  27873. var textureType = 0;
  27874. if (this._engine.getCaps().textureHalfFloatRender) {
  27875. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27876. }
  27877. else if (this._engine.getCaps().textureFloatRender) {
  27878. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27879. }
  27880. else {
  27881. throw "Depth renderer does not support int texture type";
  27882. }
  27883. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27884. }
  27885. return this._depthRenderer[camera.id];
  27886. };
  27887. /**
  27888. * Disables a depth renderer for a given camera
  27889. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27890. */
  27891. Scene.prototype.disableDepthRenderer = function (camera) {
  27892. camera = camera || this.activeCamera;
  27893. if (!camera || !this._depthRenderer[camera.id]) {
  27894. return;
  27895. }
  27896. this._depthRenderer[camera.id].dispose();
  27897. delete this._depthRenderer[camera.id];
  27898. };
  27899. /**
  27900. * Enables a GeometryBufferRender and associates it with the scene
  27901. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27902. * @returns the GeometryBufferRenderer
  27903. */
  27904. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27905. if (ratio === void 0) { ratio = 1; }
  27906. if (this._geometryBufferRenderer) {
  27907. return this._geometryBufferRenderer;
  27908. }
  27909. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27910. if (!this._geometryBufferRenderer.isSupported) {
  27911. this._geometryBufferRenderer = null;
  27912. }
  27913. return this._geometryBufferRenderer;
  27914. };
  27915. /**
  27916. * Disables the GeometryBufferRender associated with the scene
  27917. */
  27918. Scene.prototype.disableGeometryBufferRenderer = function () {
  27919. if (!this._geometryBufferRenderer) {
  27920. return;
  27921. }
  27922. this._geometryBufferRenderer.dispose();
  27923. this._geometryBufferRenderer = null;
  27924. };
  27925. /**
  27926. * Freeze all materials
  27927. * A frozen material will not be updatable but should be faster to render
  27928. */
  27929. Scene.prototype.freezeMaterials = function () {
  27930. for (var i = 0; i < this.materials.length; i++) {
  27931. this.materials[i].freeze();
  27932. }
  27933. };
  27934. /**
  27935. * Unfreeze all materials
  27936. * A frozen material will not be updatable but should be faster to render
  27937. */
  27938. Scene.prototype.unfreezeMaterials = function () {
  27939. for (var i = 0; i < this.materials.length; i++) {
  27940. this.materials[i].unfreeze();
  27941. }
  27942. };
  27943. /**
  27944. * Releases all held ressources
  27945. */
  27946. Scene.prototype.dispose = function () {
  27947. this.beforeRender = null;
  27948. this.afterRender = null;
  27949. this.skeletons = [];
  27950. this.morphTargetManagers = [];
  27951. this.importedMeshesFiles = new Array();
  27952. this.stopAllAnimations();
  27953. this.resetCachedMaterial();
  27954. for (var key in this._depthRenderer) {
  27955. this._depthRenderer[key].dispose();
  27956. }
  27957. if (this._gamepadManager) {
  27958. this._gamepadManager.dispose();
  27959. this._gamepadManager = null;
  27960. }
  27961. // Smart arrays
  27962. if (this.activeCamera) {
  27963. this.activeCamera._activeMeshes.dispose();
  27964. this.activeCamera = null;
  27965. }
  27966. this._activeMeshes.dispose();
  27967. this._renderingManager.dispose();
  27968. this._processedMaterials.dispose();
  27969. this._activeParticleSystems.dispose();
  27970. this._activeSkeletons.dispose();
  27971. this._softwareSkinnedMeshes.dispose();
  27972. this._renderTargets.dispose();
  27973. this._registeredForLateAnimationBindings.dispose();
  27974. if (this._boundingBoxRenderer) {
  27975. this._boundingBoxRenderer.dispose();
  27976. }
  27977. this._meshesForIntersections.dispose();
  27978. this._toBeDisposed.dispose();
  27979. // Abort active requests
  27980. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27981. var request = _a[_i];
  27982. request.abort();
  27983. }
  27984. // Debug layer
  27985. if (this._debugLayer) {
  27986. this._debugLayer.hide();
  27987. }
  27988. // Events
  27989. this.onDisposeObservable.notifyObservers(this);
  27990. this.onDisposeObservable.clear();
  27991. this.onBeforeRenderObservable.clear();
  27992. this.onAfterRenderObservable.clear();
  27993. this.onBeforeRenderTargetsRenderObservable.clear();
  27994. this.onAfterRenderTargetsRenderObservable.clear();
  27995. this.onAfterStepObservable.clear();
  27996. this.onBeforeStepObservable.clear();
  27997. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27998. this.onAfterActiveMeshesEvaluationObservable.clear();
  27999. this.onBeforeParticlesRenderingObservable.clear();
  28000. this.onAfterParticlesRenderingObservable.clear();
  28001. this.onBeforeSpritesRenderingObservable.clear();
  28002. this.onAfterSpritesRenderingObservable.clear();
  28003. this.onBeforeDrawPhaseObservable.clear();
  28004. this.onAfterDrawPhaseObservable.clear();
  28005. this.onBeforePhysicsObservable.clear();
  28006. this.onAfterPhysicsObservable.clear();
  28007. this.onBeforeAnimationsObservable.clear();
  28008. this.onAfterAnimationsObservable.clear();
  28009. this.onDataLoadedObservable.clear();
  28010. this.detachControl();
  28011. // Release sounds & sounds tracks
  28012. if (BABYLON.AudioEngine) {
  28013. this.disposeSounds();
  28014. }
  28015. // VR Helper
  28016. if (this.VRHelper) {
  28017. this.VRHelper.dispose();
  28018. }
  28019. // Detach cameras
  28020. var canvas = this._engine.getRenderingCanvas();
  28021. if (canvas) {
  28022. var index;
  28023. for (index = 0; index < this.cameras.length; index++) {
  28024. this.cameras[index].detachControl(canvas);
  28025. }
  28026. }
  28027. // Release animation groups
  28028. while (this.animationGroups.length) {
  28029. this.animationGroups[0].dispose();
  28030. }
  28031. // Release lights
  28032. while (this.lights.length) {
  28033. this.lights[0].dispose();
  28034. }
  28035. // Release meshes
  28036. while (this.meshes.length) {
  28037. this.meshes[0].dispose(true);
  28038. }
  28039. while (this.transformNodes.length) {
  28040. this.removeTransformNode(this.transformNodes[0]);
  28041. }
  28042. // Release cameras
  28043. while (this.cameras.length) {
  28044. this.cameras[0].dispose();
  28045. }
  28046. // Release materials
  28047. if (this.defaultMaterial) {
  28048. this.defaultMaterial.dispose();
  28049. }
  28050. while (this.multiMaterials.length) {
  28051. this.multiMaterials[0].dispose();
  28052. }
  28053. while (this.materials.length) {
  28054. this.materials[0].dispose();
  28055. }
  28056. // Release particles
  28057. while (this.particleSystems.length) {
  28058. this.particleSystems[0].dispose();
  28059. }
  28060. // Release sprites
  28061. while (this.spriteManagers.length) {
  28062. this.spriteManagers[0].dispose();
  28063. }
  28064. // Release postProcesses
  28065. while (this.postProcesses.length) {
  28066. this.postProcesses[0].dispose();
  28067. }
  28068. // Release layers
  28069. while (this.layers.length) {
  28070. this.layers[0].dispose();
  28071. }
  28072. while (this.effectLayers.length) {
  28073. this.effectLayers[0].dispose();
  28074. }
  28075. // Release textures
  28076. while (this.textures.length) {
  28077. this.textures[0].dispose();
  28078. }
  28079. // Release UBO
  28080. this._sceneUbo.dispose();
  28081. if (this._alternateSceneUbo) {
  28082. this._alternateSceneUbo.dispose();
  28083. }
  28084. // Post-processes
  28085. this.postProcessManager.dispose();
  28086. if (this._postProcessRenderPipelineManager) {
  28087. this._postProcessRenderPipelineManager.dispose();
  28088. }
  28089. // Physics
  28090. if (this._physicsEngine) {
  28091. this.disablePhysicsEngine();
  28092. }
  28093. // Remove from engine
  28094. index = this._engine.scenes.indexOf(this);
  28095. if (index > -1) {
  28096. this._engine.scenes.splice(index, 1);
  28097. }
  28098. this._engine.wipeCaches(true);
  28099. this._isDisposed = true;
  28100. };
  28101. Object.defineProperty(Scene.prototype, "isDisposed", {
  28102. /**
  28103. * Gets if the scene is already disposed
  28104. */
  28105. get: function () {
  28106. return this._isDisposed;
  28107. },
  28108. enumerable: true,
  28109. configurable: true
  28110. });
  28111. /**
  28112. * Releases sounds & soundtracks
  28113. */
  28114. Scene.prototype.disposeSounds = function () {
  28115. if (!this._mainSoundTrack) {
  28116. return;
  28117. }
  28118. this.mainSoundTrack.dispose();
  28119. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28120. this.soundTracks[scIndex].dispose();
  28121. }
  28122. };
  28123. // Octrees
  28124. /**
  28125. * Get the world extend vectors with an optional filter
  28126. *
  28127. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28128. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28129. */
  28130. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28131. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28132. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28133. filterPredicate = filterPredicate || (function () { return true; });
  28134. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28135. mesh.computeWorldMatrix(true);
  28136. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28137. return;
  28138. }
  28139. var boundingInfo = mesh.getBoundingInfo();
  28140. var minBox = boundingInfo.boundingBox.minimumWorld;
  28141. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28142. BABYLON.Tools.CheckExtends(minBox, min, max);
  28143. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28144. });
  28145. return {
  28146. min: min,
  28147. max: max
  28148. };
  28149. };
  28150. /**
  28151. * Creates or updates the octree used to boost selection (picking)
  28152. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28153. * @param maxCapacity defines the maximum capacity per leaf
  28154. * @param maxDepth defines the maximum depth of the octree
  28155. * @returns an octree of AbstractMesh
  28156. */
  28157. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28158. if (maxCapacity === void 0) { maxCapacity = 64; }
  28159. if (maxDepth === void 0) { maxDepth = 2; }
  28160. if (!this._selectionOctree) {
  28161. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28162. }
  28163. var worldExtends = this.getWorldExtends();
  28164. // Update octree
  28165. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28166. return this._selectionOctree;
  28167. };
  28168. // Picking
  28169. /**
  28170. * Creates a ray that can be used to pick in the scene
  28171. * @param x defines the x coordinate of the origin (on-screen)
  28172. * @param y defines the y coordinate of the origin (on-screen)
  28173. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28174. * @param camera defines the camera to use for the picking
  28175. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28176. * @returns a Ray
  28177. */
  28178. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28179. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28180. var result = BABYLON.Ray.Zero();
  28181. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28182. return result;
  28183. };
  28184. /**
  28185. * Creates a ray that can be used to pick in the scene
  28186. * @param x defines the x coordinate of the origin (on-screen)
  28187. * @param y defines the y coordinate of the origin (on-screen)
  28188. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28189. * @param result defines the ray where to store the picking ray
  28190. * @param camera defines the camera to use for the picking
  28191. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28192. * @returns the current scene
  28193. */
  28194. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28195. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28196. var engine = this._engine;
  28197. if (!camera) {
  28198. if (!this.activeCamera)
  28199. throw new Error("Active camera not set");
  28200. camera = this.activeCamera;
  28201. }
  28202. var cameraViewport = camera.viewport;
  28203. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28204. // Moving coordinates to local viewport world
  28205. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28206. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28207. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28208. return this;
  28209. };
  28210. /**
  28211. * Creates a ray that can be used to pick in the scene
  28212. * @param x defines the x coordinate of the origin (on-screen)
  28213. * @param y defines the y coordinate of the origin (on-screen)
  28214. * @param camera defines the camera to use for the picking
  28215. * @returns a Ray
  28216. */
  28217. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28218. var result = BABYLON.Ray.Zero();
  28219. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28220. return result;
  28221. };
  28222. /**
  28223. * Creates a ray that can be used to pick in the scene
  28224. * @param x defines the x coordinate of the origin (on-screen)
  28225. * @param y defines the y coordinate of the origin (on-screen)
  28226. * @param result defines the ray where to store the picking ray
  28227. * @param camera defines the camera to use for the picking
  28228. * @returns the current scene
  28229. */
  28230. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28231. if (!BABYLON.PickingInfo) {
  28232. return this;
  28233. }
  28234. var engine = this._engine;
  28235. if (!camera) {
  28236. if (!this.activeCamera)
  28237. throw new Error("Active camera not set");
  28238. camera = this.activeCamera;
  28239. }
  28240. var cameraViewport = camera.viewport;
  28241. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28242. var identity = BABYLON.Matrix.Identity();
  28243. // Moving coordinates to local viewport world
  28244. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28245. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28246. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28247. return this;
  28248. };
  28249. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28250. if (!BABYLON.PickingInfo) {
  28251. return null;
  28252. }
  28253. var pickingInfo = null;
  28254. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28255. var mesh = this.meshes[meshIndex];
  28256. if (predicate) {
  28257. if (!predicate(mesh)) {
  28258. continue;
  28259. }
  28260. }
  28261. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28262. continue;
  28263. }
  28264. var world = mesh.getWorldMatrix();
  28265. var ray = rayFunction(world);
  28266. var result = mesh.intersects(ray, fastCheck);
  28267. if (!result || !result.hit)
  28268. continue;
  28269. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28270. continue;
  28271. pickingInfo = result;
  28272. if (fastCheck) {
  28273. break;
  28274. }
  28275. }
  28276. return pickingInfo || new BABYLON.PickingInfo();
  28277. };
  28278. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28279. if (!BABYLON.PickingInfo) {
  28280. return null;
  28281. }
  28282. var pickingInfos = new Array();
  28283. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28284. var mesh = this.meshes[meshIndex];
  28285. if (predicate) {
  28286. if (!predicate(mesh)) {
  28287. continue;
  28288. }
  28289. }
  28290. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28291. continue;
  28292. }
  28293. var world = mesh.getWorldMatrix();
  28294. var ray = rayFunction(world);
  28295. var result = mesh.intersects(ray, false);
  28296. if (!result || !result.hit)
  28297. continue;
  28298. pickingInfos.push(result);
  28299. }
  28300. return pickingInfos;
  28301. };
  28302. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28303. if (!BABYLON.PickingInfo) {
  28304. return null;
  28305. }
  28306. var pickingInfo = null;
  28307. if (!camera) {
  28308. if (!this.activeCamera) {
  28309. return null;
  28310. }
  28311. camera = this.activeCamera;
  28312. }
  28313. if (this.spriteManagers.length > 0) {
  28314. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28315. var spriteManager = this.spriteManagers[spriteIndex];
  28316. if (!spriteManager.isPickable) {
  28317. continue;
  28318. }
  28319. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28320. if (!result || !result.hit)
  28321. continue;
  28322. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28323. continue;
  28324. pickingInfo = result;
  28325. if (fastCheck) {
  28326. break;
  28327. }
  28328. }
  28329. }
  28330. return pickingInfo || new BABYLON.PickingInfo();
  28331. };
  28332. /** Launch a ray to try to pick a mesh in the scene
  28333. * @param x position on screen
  28334. * @param y position on screen
  28335. * @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
  28336. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28337. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28338. * @returns a PickingInfo
  28339. */
  28340. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28341. var _this = this;
  28342. if (!BABYLON.PickingInfo) {
  28343. return null;
  28344. }
  28345. return this._internalPick(function (world) {
  28346. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28347. return _this._tempPickingRay;
  28348. }, predicate, fastCheck);
  28349. };
  28350. /** Launch a ray to try to pick a sprite in the scene
  28351. * @param x position on screen
  28352. * @param y position on screen
  28353. * @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
  28354. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28355. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28356. * @returns a PickingInfo
  28357. */
  28358. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28359. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28360. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28361. };
  28362. /** Use the given ray to pick a mesh in the scene
  28363. * @param ray The ray to use to pick meshes
  28364. * @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
  28365. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28366. * @returns a PickingInfo
  28367. */
  28368. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28369. var _this = this;
  28370. return this._internalPick(function (world) {
  28371. if (!_this._pickWithRayInverseMatrix) {
  28372. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28373. }
  28374. world.invertToRef(_this._pickWithRayInverseMatrix);
  28375. if (!_this._cachedRayForTransform) {
  28376. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28377. }
  28378. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28379. return _this._cachedRayForTransform;
  28380. }, predicate, fastCheck);
  28381. };
  28382. /**
  28383. * Launch a ray to try to pick a mesh in the scene
  28384. * @param x X position on screen
  28385. * @param y Y position on screen
  28386. * @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
  28387. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28388. * @returns an array of PickingInfo
  28389. */
  28390. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28391. var _this = this;
  28392. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28393. };
  28394. /**
  28395. * Launch a ray to try to pick a mesh in the scene
  28396. * @param ray Ray to use
  28397. * @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
  28398. * @returns an array of PickingInfo
  28399. */
  28400. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28401. var _this = this;
  28402. return this._internalMultiPick(function (world) {
  28403. if (!_this._pickWithRayInverseMatrix) {
  28404. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28405. }
  28406. world.invertToRef(_this._pickWithRayInverseMatrix);
  28407. if (!_this._cachedRayForTransform) {
  28408. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28409. }
  28410. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28411. return _this._cachedRayForTransform;
  28412. }, predicate);
  28413. };
  28414. /**
  28415. * Force the value of meshUnderPointer
  28416. * @param mesh defines the mesh to use
  28417. */
  28418. Scene.prototype.setPointerOverMesh = function (mesh) {
  28419. if (this._pointerOverMesh === mesh) {
  28420. return;
  28421. }
  28422. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28423. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28424. }
  28425. this._pointerOverMesh = mesh;
  28426. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28427. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28428. }
  28429. };
  28430. /**
  28431. * Gets the mesh under the pointer
  28432. * @returns a Mesh or null if no mesh is under the pointer
  28433. */
  28434. Scene.prototype.getPointerOverMesh = function () {
  28435. return this._pointerOverMesh;
  28436. };
  28437. /**
  28438. * Force the sprite under the pointer
  28439. * @param sprite defines the sprite to use
  28440. */
  28441. Scene.prototype.setPointerOverSprite = function (sprite) {
  28442. if (this._pointerOverSprite === sprite) {
  28443. return;
  28444. }
  28445. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28446. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28447. }
  28448. this._pointerOverSprite = sprite;
  28449. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28450. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28451. }
  28452. };
  28453. /**
  28454. * Gets the sprite under the pointer
  28455. * @returns a Sprite or null if no sprite is under the pointer
  28456. */
  28457. Scene.prototype.getPointerOverSprite = function () {
  28458. return this._pointerOverSprite;
  28459. };
  28460. // Physics
  28461. /**
  28462. * Gets the current physics engine
  28463. * @returns a PhysicsEngine or null if none attached
  28464. */
  28465. Scene.prototype.getPhysicsEngine = function () {
  28466. return this._physicsEngine;
  28467. };
  28468. /**
  28469. * Enables physics to the current scene
  28470. * @param gravity defines the scene's gravity for the physics engine
  28471. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28472. * @return a boolean indicating if the physics engine was initialized
  28473. */
  28474. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28475. if (gravity === void 0) { gravity = null; }
  28476. if (this._physicsEngine) {
  28477. return true;
  28478. }
  28479. try {
  28480. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28481. return true;
  28482. }
  28483. catch (e) {
  28484. BABYLON.Tools.Error(e.message);
  28485. return false;
  28486. }
  28487. };
  28488. /**
  28489. * Disables and disposes the physics engine associated with the scene
  28490. */
  28491. Scene.prototype.disablePhysicsEngine = function () {
  28492. if (!this._physicsEngine) {
  28493. return;
  28494. }
  28495. this._physicsEngine.dispose();
  28496. this._physicsEngine = null;
  28497. };
  28498. /**
  28499. * Gets a boolean indicating if there is an active physics engine
  28500. * @returns a boolean indicating if there is an active physics engine
  28501. */
  28502. Scene.prototype.isPhysicsEnabled = function () {
  28503. return this._physicsEngine !== undefined;
  28504. };
  28505. /**
  28506. * Deletes a physics compound impostor
  28507. * @param compound defines the compound to delete
  28508. */
  28509. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28510. var mesh = compound.parts[0].mesh;
  28511. if (mesh.physicsImpostor) {
  28512. mesh.physicsImpostor.dispose( /*true*/);
  28513. mesh.physicsImpostor = null;
  28514. }
  28515. };
  28516. // Misc.
  28517. /** @hidden */
  28518. Scene.prototype._rebuildGeometries = function () {
  28519. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28520. var geometry = _a[_i];
  28521. geometry._rebuild();
  28522. }
  28523. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28524. var mesh = _c[_b];
  28525. mesh._rebuild();
  28526. }
  28527. if (this.postProcessManager) {
  28528. this.postProcessManager._rebuild();
  28529. }
  28530. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28531. var layer = _e[_d];
  28532. layer._rebuild();
  28533. }
  28534. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28535. var effectLayer = _g[_f];
  28536. effectLayer._rebuild();
  28537. }
  28538. if (this._boundingBoxRenderer) {
  28539. this._boundingBoxRenderer._rebuild();
  28540. }
  28541. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28542. var system = _j[_h];
  28543. system.rebuild();
  28544. }
  28545. if (this._postProcessRenderPipelineManager) {
  28546. this._postProcessRenderPipelineManager._rebuild();
  28547. }
  28548. };
  28549. /** @hidden */
  28550. Scene.prototype._rebuildTextures = function () {
  28551. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28552. var texture = _a[_i];
  28553. texture._rebuild();
  28554. }
  28555. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28556. };
  28557. /**
  28558. * Creates a default light for the scene.
  28559. * @param replace Whether to replace the existing lights in the scene.
  28560. */
  28561. Scene.prototype.createDefaultLight = function (replace) {
  28562. if (replace === void 0) { replace = false; }
  28563. // Dispose existing light in replace mode.
  28564. if (replace) {
  28565. if (this.lights) {
  28566. for (var i = 0; i < this.lights.length; i++) {
  28567. this.lights[i].dispose();
  28568. }
  28569. }
  28570. }
  28571. // Light
  28572. if (this.lights.length === 0) {
  28573. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28574. }
  28575. };
  28576. /**
  28577. * Creates a default camera for the scene.
  28578. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28579. * @param replace Whether to replace the existing active camera in the scene.
  28580. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28581. */
  28582. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28583. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28584. if (replace === void 0) { replace = false; }
  28585. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28586. // Dispose existing camera in replace mode.
  28587. if (replace) {
  28588. if (this.activeCamera) {
  28589. this.activeCamera.dispose();
  28590. this.activeCamera = null;
  28591. }
  28592. }
  28593. // Camera
  28594. if (!this.activeCamera) {
  28595. var worldExtends = this.getWorldExtends();
  28596. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28597. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28598. var camera;
  28599. var radius = worldSize.length() * 1.5;
  28600. // empty scene scenario!
  28601. if (!isFinite(radius)) {
  28602. radius = 1;
  28603. worldCenter.copyFromFloats(0, 0, 0);
  28604. }
  28605. if (createArcRotateCamera) {
  28606. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28607. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28608. arcRotateCamera.wheelPrecision = 100 / radius;
  28609. camera = arcRotateCamera;
  28610. }
  28611. else {
  28612. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28613. freeCamera.setTarget(worldCenter);
  28614. camera = freeCamera;
  28615. }
  28616. camera.minZ = radius * 0.01;
  28617. camera.maxZ = radius * 1000;
  28618. camera.speed = radius * 0.2;
  28619. this.activeCamera = camera;
  28620. var canvas = this.getEngine().getRenderingCanvas();
  28621. if (attachCameraControls && canvas) {
  28622. camera.attachControl(canvas);
  28623. }
  28624. }
  28625. };
  28626. /**
  28627. * Creates a default camera and a default light
  28628. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28629. * @param replace defines if the camera and/or light will replace the existing ones
  28630. * @param attachCameraControls defines if attachControl will be called on the new camera
  28631. */
  28632. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28633. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28634. if (replace === void 0) { replace = false; }
  28635. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28636. this.createDefaultLight(replace);
  28637. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28638. };
  28639. /**
  28640. * Creates a new sky box
  28641. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28642. * @param environmentTexture defines the texture to use as environment texture
  28643. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28644. * @param scale defines the overall scale of the skybox
  28645. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28646. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28647. * @returns a new mesh holding the sky box
  28648. */
  28649. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28650. if (pbr === void 0) { pbr = false; }
  28651. if (scale === void 0) { scale = 1000; }
  28652. if (blur === void 0) { blur = 0; }
  28653. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28654. if (!environmentTexture) {
  28655. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28656. return null;
  28657. }
  28658. if (setGlobalEnvTexture) {
  28659. if (environmentTexture) {
  28660. this.environmentTexture = environmentTexture;
  28661. }
  28662. }
  28663. // Skybox
  28664. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28665. if (pbr) {
  28666. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28667. hdrSkyboxMaterial.backFaceCulling = false;
  28668. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28669. if (hdrSkyboxMaterial.reflectionTexture) {
  28670. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28671. }
  28672. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28673. hdrSkyboxMaterial.disableLighting = true;
  28674. hdrSkyboxMaterial.twoSidedLighting = true;
  28675. hdrSkybox.infiniteDistance = true;
  28676. hdrSkybox.material = hdrSkyboxMaterial;
  28677. }
  28678. else {
  28679. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28680. skyboxMaterial.backFaceCulling = false;
  28681. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28682. if (skyboxMaterial.reflectionTexture) {
  28683. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28684. }
  28685. skyboxMaterial.disableLighting = true;
  28686. hdrSkybox.infiniteDistance = true;
  28687. hdrSkybox.material = skyboxMaterial;
  28688. }
  28689. return hdrSkybox;
  28690. };
  28691. /**
  28692. * Creates a new environment
  28693. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28694. * @param options defines the options you can use to configure the environment
  28695. * @returns the new EnvironmentHelper
  28696. */
  28697. Scene.prototype.createDefaultEnvironment = function (options) {
  28698. if (BABYLON.EnvironmentHelper) {
  28699. return new BABYLON.EnvironmentHelper(options, this);
  28700. }
  28701. return null;
  28702. };
  28703. /**
  28704. * Creates a new VREXperienceHelper
  28705. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28706. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28707. * @returns a new VREXperienceHelper
  28708. */
  28709. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28710. if (webVROptions === void 0) { webVROptions = {}; }
  28711. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28712. };
  28713. // Tags
  28714. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28715. if (tagsQuery === undefined) {
  28716. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28717. return list;
  28718. }
  28719. var listByTags = [];
  28720. forEach = forEach || (function (item) { return; });
  28721. for (var i in list) {
  28722. var item = list[i];
  28723. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28724. listByTags.push(item);
  28725. forEach(item);
  28726. }
  28727. }
  28728. return listByTags;
  28729. };
  28730. /**
  28731. * Get a list of meshes by tags
  28732. * @param tagsQuery defines the tags query to use
  28733. * @param forEach defines a predicate used to filter results
  28734. * @returns an array of Mesh
  28735. */
  28736. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28737. return this._getByTags(this.meshes, tagsQuery, forEach);
  28738. };
  28739. /**
  28740. * Get a list of cameras by tags
  28741. * @param tagsQuery defines the tags query to use
  28742. * @param forEach defines a predicate used to filter results
  28743. * @returns an array of Camera
  28744. */
  28745. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28746. return this._getByTags(this.cameras, tagsQuery, forEach);
  28747. };
  28748. /**
  28749. * Get a list of lights by tags
  28750. * @param tagsQuery defines the tags query to use
  28751. * @param forEach defines a predicate used to filter results
  28752. * @returns an array of Light
  28753. */
  28754. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28755. return this._getByTags(this.lights, tagsQuery, forEach);
  28756. };
  28757. /**
  28758. * Get a list of materials by tags
  28759. * @param tagsQuery defines the tags query to use
  28760. * @param forEach defines a predicate used to filter results
  28761. * @returns an array of Material
  28762. */
  28763. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28764. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28765. };
  28766. /**
  28767. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28768. * This allowed control for front to back rendering or reversly depending of the special needs.
  28769. *
  28770. * @param renderingGroupId The rendering group id corresponding to its index
  28771. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28772. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28773. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28774. */
  28775. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28776. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28777. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28778. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28779. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28780. };
  28781. /**
  28782. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28783. *
  28784. * @param renderingGroupId The rendering group id corresponding to its index
  28785. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28786. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28787. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28788. */
  28789. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28790. if (depth === void 0) { depth = true; }
  28791. if (stencil === void 0) { stencil = true; }
  28792. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28793. };
  28794. /**
  28795. * Will flag all materials as dirty to trigger new shader compilation
  28796. * @param flag defines the flag used to specify which material part must be marked as dirty
  28797. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28798. */
  28799. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28800. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28801. var material = _a[_i];
  28802. if (predicate && !predicate(material)) {
  28803. continue;
  28804. }
  28805. material.markAsDirty(flag);
  28806. }
  28807. };
  28808. /** @hidden */
  28809. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28810. var _this = this;
  28811. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28812. this._activeRequests.push(request);
  28813. request.onCompleteObservable.add(function (request) {
  28814. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28815. });
  28816. return request;
  28817. };
  28818. /** @hidden */
  28819. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28820. var _this = this;
  28821. return new Promise(function (resolve, reject) {
  28822. _this._loadFile(url, function (data) {
  28823. resolve(data);
  28824. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28825. reject(exception);
  28826. });
  28827. });
  28828. };
  28829. // Statics
  28830. Scene._FOGMODE_NONE = 0;
  28831. Scene._FOGMODE_EXP = 1;
  28832. Scene._FOGMODE_EXP2 = 2;
  28833. Scene._FOGMODE_LINEAR = 3;
  28834. Scene._uniqueIdCounter = 0;
  28835. /**
  28836. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28837. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28838. */
  28839. Scene.MinDeltaTime = 1.0;
  28840. /**
  28841. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28842. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28843. */
  28844. Scene.MaxDeltaTime = 1000.0;
  28845. /** The distance in pixel that you have to move to prevent some events */
  28846. Scene.DragMovementThreshold = 10; // in pixels
  28847. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28848. Scene.LongPressDelay = 500; // in milliseconds
  28849. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28850. Scene.DoubleClickDelay = 300; // in milliseconds
  28851. /** If you need to check double click without raising a single click at first click, enable this flag */
  28852. Scene.ExclusiveDoubleClickMode = false;
  28853. return Scene;
  28854. }());
  28855. BABYLON.Scene = Scene;
  28856. })(BABYLON || (BABYLON = {}));
  28857. //# sourceMappingURL=babylon.scene.js.map
  28858. var BABYLON;
  28859. (function (BABYLON) {
  28860. /**
  28861. * Set of assets to keep when moving a scene into an asset container.
  28862. */
  28863. var KeepAssets = /** @class */ (function () {
  28864. function KeepAssets() {
  28865. /**
  28866. * Cameras to keep.
  28867. */
  28868. this.cameras = new Array();
  28869. /**
  28870. * Lights to keep.
  28871. */
  28872. this.lights = new Array();
  28873. /**
  28874. * Meshes to keep.
  28875. */
  28876. this.meshes = new Array();
  28877. /**
  28878. * Skeletons to keep.
  28879. */
  28880. this.skeletons = new Array();
  28881. /**
  28882. * ParticleSystems to keep.
  28883. */
  28884. this.particleSystems = new Array();
  28885. /**
  28886. * Animations to keep.
  28887. */
  28888. this.animations = new Array();
  28889. /**
  28890. * AnimationGroups to keep.
  28891. */
  28892. this.animationGroups = new Array();
  28893. /**
  28894. * MultiMaterials to keep.
  28895. */
  28896. this.multiMaterials = new Array();
  28897. /**
  28898. * Materials to keep.
  28899. */
  28900. this.materials = new Array();
  28901. /**
  28902. * MorphTargetManagers to keep.
  28903. */
  28904. this.morphTargetManagers = new Array();
  28905. /**
  28906. * Geometries to keep.
  28907. */
  28908. this.geometries = new Array();
  28909. /**
  28910. * TransformNodes to keep.
  28911. */
  28912. this.transformNodes = new Array();
  28913. /**
  28914. * LensFlareSystems to keep.
  28915. */
  28916. this.lensFlareSystems = new Array();
  28917. /**
  28918. * ShadowGenerators to keep.
  28919. */
  28920. this.shadowGenerators = new Array();
  28921. /**
  28922. * ActionManagers to keep.
  28923. */
  28924. this.actionManagers = new Array();
  28925. /**
  28926. * Sounds to keep.
  28927. */
  28928. this.sounds = new Array();
  28929. /**
  28930. * Textures to keep.
  28931. */
  28932. this.textures = new Array();
  28933. /**
  28934. * Effect layers to keep.
  28935. */
  28936. this.effectLayers = new Array();
  28937. }
  28938. return KeepAssets;
  28939. }());
  28940. BABYLON.KeepAssets = KeepAssets;
  28941. /**
  28942. * Container with a set of assets that can be added or removed from a scene.
  28943. */
  28944. var AssetContainer = /** @class */ (function () {
  28945. /**
  28946. * Instantiates an AssetContainer.
  28947. * @param scene The scene the AssetContainer belongs to.
  28948. */
  28949. function AssetContainer(scene) {
  28950. // Objects
  28951. /**
  28952. * Cameras populated in the container.
  28953. */
  28954. this.cameras = new Array();
  28955. /**
  28956. * Lights populated in the container.
  28957. */
  28958. this.lights = new Array();
  28959. /**
  28960. * Meshes populated in the container.
  28961. */
  28962. this.meshes = new Array();
  28963. /**
  28964. * Skeletons populated in the container.
  28965. */
  28966. this.skeletons = new Array();
  28967. /**
  28968. * ParticleSystems populated in the container.
  28969. */
  28970. this.particleSystems = new Array();
  28971. /**
  28972. * Animations populated in the container.
  28973. */
  28974. this.animations = new Array();
  28975. /**
  28976. * AnimationGroups populated in the container.
  28977. */
  28978. this.animationGroups = new Array();
  28979. /**
  28980. * MultiMaterials populated in the container.
  28981. */
  28982. this.multiMaterials = new Array();
  28983. /**
  28984. * Materials populated in the container.
  28985. */
  28986. this.materials = new Array();
  28987. /**
  28988. * MorphTargetManagers populated in the container.
  28989. */
  28990. this.morphTargetManagers = new Array();
  28991. /**
  28992. * Geometries populated in the container.
  28993. */
  28994. this.geometries = new Array();
  28995. /**
  28996. * TransformNodes populated in the container.
  28997. */
  28998. this.transformNodes = new Array();
  28999. /**
  29000. * LensFlareSystems populated in the container.
  29001. */
  29002. this.lensFlareSystems = new Array();
  29003. /**
  29004. * ShadowGenerators populated in the container.
  29005. */
  29006. this.shadowGenerators = new Array();
  29007. /**
  29008. * ActionManagers populated in the container.
  29009. */
  29010. this.actionManagers = new Array();
  29011. /**
  29012. * Sounds populated in the container.
  29013. */
  29014. this.sounds = new Array();
  29015. /**
  29016. * Textures populated in the container.
  29017. */
  29018. this.textures = new Array();
  29019. /**
  29020. * Effect layers populated in the container.
  29021. */
  29022. this.effectLayers = new Array();
  29023. this.scene = scene;
  29024. }
  29025. /**
  29026. * Adds all the assets from the container to the scene.
  29027. */
  29028. AssetContainer.prototype.addAllToScene = function () {
  29029. var _this = this;
  29030. this.cameras.forEach(function (o) {
  29031. _this.scene.addCamera(o);
  29032. });
  29033. this.lights.forEach(function (o) {
  29034. _this.scene.addLight(o);
  29035. });
  29036. this.meshes.forEach(function (o) {
  29037. _this.scene.addMesh(o);
  29038. });
  29039. this.skeletons.forEach(function (o) {
  29040. _this.scene.addSkeleton(o);
  29041. });
  29042. this.particleSystems.forEach(function (o) {
  29043. _this.scene.addParticleSystem(o);
  29044. });
  29045. this.animations.forEach(function (o) {
  29046. _this.scene.addAnimation(o);
  29047. });
  29048. this.animationGroups.forEach(function (o) {
  29049. _this.scene.addAnimationGroup(o);
  29050. });
  29051. this.multiMaterials.forEach(function (o) {
  29052. _this.scene.addMultiMaterial(o);
  29053. });
  29054. this.materials.forEach(function (o) {
  29055. _this.scene.addMaterial(o);
  29056. });
  29057. this.morphTargetManagers.forEach(function (o) {
  29058. _this.scene.addMorphTargetManager(o);
  29059. });
  29060. this.geometries.forEach(function (o) {
  29061. _this.scene.addGeometry(o);
  29062. });
  29063. this.transformNodes.forEach(function (o) {
  29064. _this.scene.addTransformNode(o);
  29065. });
  29066. this.lensFlareSystems.forEach(function (o) {
  29067. _this.scene.addLensFlareSystem(o);
  29068. });
  29069. this.actionManagers.forEach(function (o) {
  29070. _this.scene.addActionManager(o);
  29071. });
  29072. this.sounds.forEach(function (o) {
  29073. o.play();
  29074. o.autoplay = true;
  29075. _this.scene.mainSoundTrack.AddSound(o);
  29076. });
  29077. this.textures.forEach(function (o) {
  29078. _this.scene.addTexture(o);
  29079. });
  29080. this.effectLayers.forEach(function (o) {
  29081. _this.scene.addEffectLayer(o);
  29082. });
  29083. };
  29084. /**
  29085. * Removes all the assets in the container from the scene
  29086. */
  29087. AssetContainer.prototype.removeAllFromScene = function () {
  29088. var _this = this;
  29089. this.cameras.forEach(function (o) {
  29090. _this.scene.removeCamera(o);
  29091. });
  29092. this.lights.forEach(function (o) {
  29093. _this.scene.removeLight(o);
  29094. });
  29095. this.meshes.forEach(function (o) {
  29096. _this.scene.removeMesh(o);
  29097. });
  29098. this.skeletons.forEach(function (o) {
  29099. _this.scene.removeSkeleton(o);
  29100. });
  29101. this.particleSystems.forEach(function (o) {
  29102. _this.scene.removeParticleSystem(o);
  29103. });
  29104. this.animations.forEach(function (o) {
  29105. _this.scene.removeAnimation(o);
  29106. });
  29107. this.animationGroups.forEach(function (o) {
  29108. _this.scene.removeAnimationGroup(o);
  29109. });
  29110. this.multiMaterials.forEach(function (o) {
  29111. _this.scene.removeMultiMaterial(o);
  29112. });
  29113. this.materials.forEach(function (o) {
  29114. _this.scene.removeMaterial(o);
  29115. });
  29116. this.morphTargetManagers.forEach(function (o) {
  29117. _this.scene.removeMorphTargetManager(o);
  29118. });
  29119. this.geometries.forEach(function (o) {
  29120. _this.scene.removeGeometry(o);
  29121. });
  29122. this.transformNodes.forEach(function (o) {
  29123. _this.scene.removeTransformNode(o);
  29124. });
  29125. this.lensFlareSystems.forEach(function (o) {
  29126. _this.scene.removeLensFlareSystem(o);
  29127. });
  29128. this.actionManagers.forEach(function (o) {
  29129. _this.scene.removeActionManager(o);
  29130. });
  29131. this.sounds.forEach(function (o) {
  29132. o.stop();
  29133. o.autoplay = false;
  29134. _this.scene.mainSoundTrack.RemoveSound(o);
  29135. });
  29136. this.textures.forEach(function (o) {
  29137. _this.scene.removeTexture(o);
  29138. });
  29139. this.effectLayers.forEach(function (o) {
  29140. _this.scene.removeEffectLayer(o);
  29141. });
  29142. };
  29143. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29144. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29145. var asset = sourceAssets_1[_i];
  29146. var move = true;
  29147. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29148. var keepAsset = keepAssets_1[_a];
  29149. if (asset === keepAsset) {
  29150. move = false;
  29151. break;
  29152. }
  29153. }
  29154. if (move) {
  29155. targetAssets.push(asset);
  29156. }
  29157. }
  29158. };
  29159. /**
  29160. * Removes all the assets contained in the scene and adds them to the container.
  29161. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29162. */
  29163. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29164. if (keepAssets === undefined) {
  29165. keepAssets = new KeepAssets();
  29166. }
  29167. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29168. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29169. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29170. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29171. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29172. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29173. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29174. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29175. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29176. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29177. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29178. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29179. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29180. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29181. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29182. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29183. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29184. this.removeAllFromScene();
  29185. };
  29186. return AssetContainer;
  29187. }());
  29188. BABYLON.AssetContainer = AssetContainer;
  29189. })(BABYLON || (BABYLON = {}));
  29190. //# sourceMappingURL=babylon.assetContainer.js.map
  29191. var BABYLON;
  29192. (function (BABYLON) {
  29193. var Buffer = /** @class */ (function () {
  29194. /**
  29195. * Constructor
  29196. * @param engine the engine
  29197. * @param data the data to use for this buffer
  29198. * @param updatable whether the data is updatable
  29199. * @param stride the stride (optional)
  29200. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29201. * @param instanced whether the buffer is instanced (optional)
  29202. * @param useBytes set to true if the stride in in bytes (optional)
  29203. */
  29204. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29205. if (stride === void 0) { stride = 0; }
  29206. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29207. if (instanced === void 0) { instanced = false; }
  29208. if (useBytes === void 0) { useBytes = false; }
  29209. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29210. this._engine = engine.getScene().getEngine();
  29211. }
  29212. else {
  29213. this._engine = engine;
  29214. }
  29215. this._updatable = updatable;
  29216. this._instanced = instanced;
  29217. this._data = data;
  29218. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29219. if (!postponeInternalCreation) { // by default
  29220. this.create();
  29221. }
  29222. }
  29223. /**
  29224. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29225. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29226. * @param offset defines offset in the buffer (0 by default)
  29227. * @param size defines the size in floats of attributes (position is 3 for instance)
  29228. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29229. * @param instanced defines if the vertex buffer contains indexed data
  29230. * @param useBytes defines if the offset and stride are in bytes
  29231. * @returns the new vertex buffer
  29232. */
  29233. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29234. if (useBytes === void 0) { useBytes = false; }
  29235. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29236. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29237. // a lot of these parameters are ignored as they are overriden by the buffer
  29238. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29239. };
  29240. // Properties
  29241. Buffer.prototype.isUpdatable = function () {
  29242. return this._updatable;
  29243. };
  29244. Buffer.prototype.getData = function () {
  29245. return this._data;
  29246. };
  29247. Buffer.prototype.getBuffer = function () {
  29248. return this._buffer;
  29249. };
  29250. /**
  29251. * Gets the stride in float32 units (i.e. byte stride / 4).
  29252. * May not be an integer if the byte stride is not divisible by 4.
  29253. * DEPRECATED. Use byteStride instead.
  29254. * @returns the stride in float32 units
  29255. */
  29256. Buffer.prototype.getStrideSize = function () {
  29257. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29258. };
  29259. // Methods
  29260. Buffer.prototype.create = function (data) {
  29261. if (data === void 0) { data = null; }
  29262. if (!data && this._buffer) {
  29263. return; // nothing to do
  29264. }
  29265. data = data || this._data;
  29266. if (!data) {
  29267. return;
  29268. }
  29269. if (!this._buffer) { // create buffer
  29270. if (this._updatable) {
  29271. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29272. this._data = data;
  29273. }
  29274. else {
  29275. this._buffer = this._engine.createVertexBuffer(data);
  29276. }
  29277. }
  29278. else if (this._updatable) { // update buffer
  29279. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29280. this._data = data;
  29281. }
  29282. };
  29283. Buffer.prototype._rebuild = function () {
  29284. this._buffer = null;
  29285. this.create(this._data);
  29286. };
  29287. Buffer.prototype.update = function (data) {
  29288. this.create(data);
  29289. };
  29290. /**
  29291. * Updates the data directly.
  29292. * @param data the new data
  29293. * @param offset the new offset
  29294. * @param vertexCount the vertex count (optional)
  29295. * @param useBytes set to true if the offset is in bytes
  29296. */
  29297. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29298. if (useBytes === void 0) { useBytes = false; }
  29299. if (!this._buffer) {
  29300. return;
  29301. }
  29302. if (this._updatable) { // update buffer
  29303. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29304. this._data = null;
  29305. }
  29306. };
  29307. Buffer.prototype.dispose = function () {
  29308. if (!this._buffer) {
  29309. return;
  29310. }
  29311. if (this._engine._releaseBuffer(this._buffer)) {
  29312. this._buffer = null;
  29313. }
  29314. };
  29315. return Buffer;
  29316. }());
  29317. BABYLON.Buffer = Buffer;
  29318. })(BABYLON || (BABYLON = {}));
  29319. //# sourceMappingURL=babylon.buffer.js.map
  29320. var BABYLON;
  29321. (function (BABYLON) {
  29322. var VertexBuffer = /** @class */ (function () {
  29323. /**
  29324. * Constructor
  29325. * @param engine the engine
  29326. * @param data the data to use for this vertex buffer
  29327. * @param kind the vertex buffer kind
  29328. * @param updatable whether the data is updatable
  29329. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29330. * @param stride the stride (optional)
  29331. * @param instanced whether the buffer is instanced (optional)
  29332. * @param offset the offset of the data (optional)
  29333. * @param size the number of components (optional)
  29334. * @param type the type of the component (optional)
  29335. * @param normalized whether the data contains normalized data (optional)
  29336. * @param useBytes set to true if stride and offset are in bytes (optional)
  29337. */
  29338. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29339. if (normalized === void 0) { normalized = false; }
  29340. if (useBytes === void 0) { useBytes = false; }
  29341. if (data instanceof BABYLON.Buffer) {
  29342. this._buffer = data;
  29343. this._ownsBuffer = false;
  29344. }
  29345. else {
  29346. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29347. this._ownsBuffer = true;
  29348. }
  29349. this._kind = kind;
  29350. if (type == undefined) {
  29351. var data_1 = this.getData();
  29352. this.type = VertexBuffer.FLOAT;
  29353. if (data_1 instanceof Int8Array)
  29354. this.type = VertexBuffer.BYTE;
  29355. else if (data_1 instanceof Uint8Array)
  29356. this.type = VertexBuffer.UNSIGNED_BYTE;
  29357. else if (data_1 instanceof Int16Array)
  29358. this.type = VertexBuffer.SHORT;
  29359. else if (data_1 instanceof Uint16Array)
  29360. this.type = VertexBuffer.UNSIGNED_SHORT;
  29361. else if (data_1 instanceof Int32Array)
  29362. this.type = VertexBuffer.INT;
  29363. else if (data_1 instanceof Uint32Array)
  29364. this.type = VertexBuffer.UNSIGNED_INT;
  29365. }
  29366. else {
  29367. this.type = type;
  29368. }
  29369. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29370. if (useBytes) {
  29371. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29372. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29373. this.byteOffset = offset || 0;
  29374. }
  29375. else {
  29376. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29377. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29378. this.byteOffset = (offset || 0) * typeByteLength;
  29379. }
  29380. this.normalized = normalized;
  29381. this._instanced = instanced !== undefined ? instanced : false;
  29382. this._instanceDivisor = instanced ? 1 : 0;
  29383. }
  29384. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29385. /**
  29386. * Gets or sets the instance divisor when in instanced mode
  29387. */
  29388. get: function () {
  29389. return this._instanceDivisor;
  29390. },
  29391. set: function (value) {
  29392. this._instanceDivisor = value;
  29393. if (value == 0) {
  29394. this._instanced = false;
  29395. }
  29396. else {
  29397. this._instanced = true;
  29398. }
  29399. },
  29400. enumerable: true,
  29401. configurable: true
  29402. });
  29403. VertexBuffer.prototype._rebuild = function () {
  29404. if (!this._buffer) {
  29405. return;
  29406. }
  29407. this._buffer._rebuild();
  29408. };
  29409. /**
  29410. * Returns the kind of the VertexBuffer (string).
  29411. */
  29412. VertexBuffer.prototype.getKind = function () {
  29413. return this._kind;
  29414. };
  29415. // Properties
  29416. /**
  29417. * Boolean : is the VertexBuffer updatable ?
  29418. */
  29419. VertexBuffer.prototype.isUpdatable = function () {
  29420. return this._buffer.isUpdatable();
  29421. };
  29422. /**
  29423. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29424. */
  29425. VertexBuffer.prototype.getData = function () {
  29426. return this._buffer.getData();
  29427. };
  29428. /**
  29429. * Returns the WebGLBuffer associated to the VertexBuffer.
  29430. */
  29431. VertexBuffer.prototype.getBuffer = function () {
  29432. return this._buffer.getBuffer();
  29433. };
  29434. /**
  29435. * Returns the stride as a multiple of the type byte length.
  29436. * DEPRECATED. Use byteStride instead.
  29437. */
  29438. VertexBuffer.prototype.getStrideSize = function () {
  29439. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29440. };
  29441. /**
  29442. * Returns the offset as a multiple of the type byte length.
  29443. * DEPRECATED. Use byteOffset instead.
  29444. */
  29445. VertexBuffer.prototype.getOffset = function () {
  29446. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29447. };
  29448. /**
  29449. * Returns the number of components per vertex attribute (integer).
  29450. */
  29451. VertexBuffer.prototype.getSize = function () {
  29452. return this._size;
  29453. };
  29454. /**
  29455. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29456. */
  29457. VertexBuffer.prototype.getIsInstanced = function () {
  29458. return this._instanced;
  29459. };
  29460. /**
  29461. * Returns the instancing divisor, zero for non-instanced (integer).
  29462. */
  29463. VertexBuffer.prototype.getInstanceDivisor = function () {
  29464. return this._instanceDivisor;
  29465. };
  29466. // Methods
  29467. /**
  29468. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29469. * Returns the created WebGLBuffer.
  29470. */
  29471. VertexBuffer.prototype.create = function (data) {
  29472. return this._buffer.create(data);
  29473. };
  29474. /**
  29475. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29476. * This function will create a new buffer if the current one is not updatable
  29477. * Returns the updated WebGLBuffer.
  29478. */
  29479. VertexBuffer.prototype.update = function (data) {
  29480. return this._buffer.update(data);
  29481. };
  29482. /**
  29483. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29484. * Returns the directly updated WebGLBuffer.
  29485. * @param data the new data
  29486. * @param offset the new offset
  29487. * @param useBytes set to true if the offset is in bytes
  29488. */
  29489. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29490. if (useBytes === void 0) { useBytes = false; }
  29491. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29492. };
  29493. /**
  29494. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29495. */
  29496. VertexBuffer.prototype.dispose = function () {
  29497. if (this._ownsBuffer) {
  29498. this._buffer.dispose();
  29499. }
  29500. };
  29501. /**
  29502. * Enumerates each value of this vertex buffer as numbers.
  29503. * @param count the number of values to enumerate
  29504. * @param callback the callback function called for each value
  29505. */
  29506. VertexBuffer.prototype.forEach = function (count, callback) {
  29507. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29508. };
  29509. Object.defineProperty(VertexBuffer, "PositionKind", {
  29510. get: function () {
  29511. return VertexBuffer._PositionKind;
  29512. },
  29513. enumerable: true,
  29514. configurable: true
  29515. });
  29516. Object.defineProperty(VertexBuffer, "NormalKind", {
  29517. get: function () {
  29518. return VertexBuffer._NormalKind;
  29519. },
  29520. enumerable: true,
  29521. configurable: true
  29522. });
  29523. Object.defineProperty(VertexBuffer, "TangentKind", {
  29524. get: function () {
  29525. return VertexBuffer._TangentKind;
  29526. },
  29527. enumerable: true,
  29528. configurable: true
  29529. });
  29530. Object.defineProperty(VertexBuffer, "UVKind", {
  29531. get: function () {
  29532. return VertexBuffer._UVKind;
  29533. },
  29534. enumerable: true,
  29535. configurable: true
  29536. });
  29537. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29538. get: function () {
  29539. return VertexBuffer._UV2Kind;
  29540. },
  29541. enumerable: true,
  29542. configurable: true
  29543. });
  29544. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29545. get: function () {
  29546. return VertexBuffer._UV3Kind;
  29547. },
  29548. enumerable: true,
  29549. configurable: true
  29550. });
  29551. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29552. get: function () {
  29553. return VertexBuffer._UV4Kind;
  29554. },
  29555. enumerable: true,
  29556. configurable: true
  29557. });
  29558. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29559. get: function () {
  29560. return VertexBuffer._UV5Kind;
  29561. },
  29562. enumerable: true,
  29563. configurable: true
  29564. });
  29565. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29566. get: function () {
  29567. return VertexBuffer._UV6Kind;
  29568. },
  29569. enumerable: true,
  29570. configurable: true
  29571. });
  29572. Object.defineProperty(VertexBuffer, "ColorKind", {
  29573. get: function () {
  29574. return VertexBuffer._ColorKind;
  29575. },
  29576. enumerable: true,
  29577. configurable: true
  29578. });
  29579. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29580. get: function () {
  29581. return VertexBuffer._MatricesIndicesKind;
  29582. },
  29583. enumerable: true,
  29584. configurable: true
  29585. });
  29586. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29587. get: function () {
  29588. return VertexBuffer._MatricesWeightsKind;
  29589. },
  29590. enumerable: true,
  29591. configurable: true
  29592. });
  29593. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29594. get: function () {
  29595. return VertexBuffer._MatricesIndicesExtraKind;
  29596. },
  29597. enumerable: true,
  29598. configurable: true
  29599. });
  29600. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29601. get: function () {
  29602. return VertexBuffer._MatricesWeightsExtraKind;
  29603. },
  29604. enumerable: true,
  29605. configurable: true
  29606. });
  29607. /**
  29608. * Deduces the stride given a kind.
  29609. * @param kind The kind string to deduce
  29610. * @returns The deduced stride
  29611. */
  29612. VertexBuffer.DeduceStride = function (kind) {
  29613. switch (kind) {
  29614. case VertexBuffer.UVKind:
  29615. case VertexBuffer.UV2Kind:
  29616. case VertexBuffer.UV3Kind:
  29617. case VertexBuffer.UV4Kind:
  29618. case VertexBuffer.UV5Kind:
  29619. case VertexBuffer.UV6Kind:
  29620. return 2;
  29621. case VertexBuffer.NormalKind:
  29622. case VertexBuffer.PositionKind:
  29623. return 3;
  29624. case VertexBuffer.ColorKind:
  29625. case VertexBuffer.MatricesIndicesKind:
  29626. case VertexBuffer.MatricesIndicesExtraKind:
  29627. case VertexBuffer.MatricesWeightsKind:
  29628. case VertexBuffer.MatricesWeightsExtraKind:
  29629. case VertexBuffer.TangentKind:
  29630. return 4;
  29631. default:
  29632. throw new Error("Invalid kind '" + kind + "'");
  29633. }
  29634. };
  29635. /**
  29636. * Gets the byte length of the given type.
  29637. * @param type the type
  29638. * @returns the number of bytes
  29639. */
  29640. VertexBuffer.GetTypeByteLength = function (type) {
  29641. switch (type) {
  29642. case VertexBuffer.BYTE:
  29643. case VertexBuffer.UNSIGNED_BYTE:
  29644. return 1;
  29645. case VertexBuffer.SHORT:
  29646. case VertexBuffer.UNSIGNED_SHORT:
  29647. return 2;
  29648. case VertexBuffer.INT:
  29649. case VertexBuffer.FLOAT:
  29650. return 4;
  29651. default:
  29652. throw new Error("Invalid type '" + type + "'");
  29653. }
  29654. };
  29655. /**
  29656. * Enumerates each value of the given parameters as numbers.
  29657. * @param data the data to enumerate
  29658. * @param byteOffset the byte offset of the data
  29659. * @param byteStride the byte stride of the data
  29660. * @param componentCount the number of components per element
  29661. * @param componentType the type of the component
  29662. * @param count the total number of components
  29663. * @param normalized whether the data is normalized
  29664. * @param callback the callback function called for each value
  29665. */
  29666. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29667. if (data instanceof Array) {
  29668. var offset = byteOffset / 4;
  29669. var stride = byteStride / 4;
  29670. for (var index = 0; index < count; index += componentCount) {
  29671. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29672. callback(data[offset + componentIndex], index + componentIndex);
  29673. }
  29674. offset += stride;
  29675. }
  29676. }
  29677. else {
  29678. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29679. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29680. for (var index = 0; index < count; index += componentCount) {
  29681. var componentByteOffset = byteOffset;
  29682. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29683. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29684. callback(value, index + componentIndex);
  29685. componentByteOffset += componentByteLength;
  29686. }
  29687. byteOffset += byteStride;
  29688. }
  29689. }
  29690. };
  29691. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29692. switch (type) {
  29693. case VertexBuffer.BYTE: {
  29694. var value = dataView.getInt8(byteOffset);
  29695. if (normalized) {
  29696. value = Math.max(value / 127, -1);
  29697. }
  29698. return value;
  29699. }
  29700. case VertexBuffer.UNSIGNED_BYTE: {
  29701. var value = dataView.getUint8(byteOffset);
  29702. if (normalized) {
  29703. value = value / 255;
  29704. }
  29705. return value;
  29706. }
  29707. case VertexBuffer.SHORT: {
  29708. var value = dataView.getInt16(byteOffset, true);
  29709. if (normalized) {
  29710. value = Math.max(value / 16383, -1);
  29711. }
  29712. return value;
  29713. }
  29714. case VertexBuffer.UNSIGNED_SHORT: {
  29715. var value = dataView.getUint16(byteOffset, true);
  29716. if (normalized) {
  29717. value = value / 65535;
  29718. }
  29719. return value;
  29720. }
  29721. case VertexBuffer.FLOAT: {
  29722. return dataView.getFloat32(byteOffset, true);
  29723. }
  29724. default: {
  29725. throw new Error("Invalid component type " + type);
  29726. }
  29727. }
  29728. };
  29729. /**
  29730. * The byte type.
  29731. */
  29732. VertexBuffer.BYTE = 5120;
  29733. /**
  29734. * The unsigned byte type.
  29735. */
  29736. VertexBuffer.UNSIGNED_BYTE = 5121;
  29737. /**
  29738. * The short type.
  29739. */
  29740. VertexBuffer.SHORT = 5122;
  29741. /**
  29742. * The unsigned short type.
  29743. */
  29744. VertexBuffer.UNSIGNED_SHORT = 5123;
  29745. /**
  29746. * The integer type.
  29747. */
  29748. VertexBuffer.INT = 5124;
  29749. /**
  29750. * The unsigned integer type.
  29751. */
  29752. VertexBuffer.UNSIGNED_INT = 5125;
  29753. /**
  29754. * The float type.
  29755. */
  29756. VertexBuffer.FLOAT = 5126;
  29757. // Enums
  29758. VertexBuffer._PositionKind = "position";
  29759. VertexBuffer._NormalKind = "normal";
  29760. VertexBuffer._TangentKind = "tangent";
  29761. VertexBuffer._UVKind = "uv";
  29762. VertexBuffer._UV2Kind = "uv2";
  29763. VertexBuffer._UV3Kind = "uv3";
  29764. VertexBuffer._UV4Kind = "uv4";
  29765. VertexBuffer._UV5Kind = "uv5";
  29766. VertexBuffer._UV6Kind = "uv6";
  29767. VertexBuffer._ColorKind = "color";
  29768. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29769. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29770. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29771. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29772. return VertexBuffer;
  29773. }());
  29774. BABYLON.VertexBuffer = VertexBuffer;
  29775. })(BABYLON || (BABYLON = {}));
  29776. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29777. var BABYLON;
  29778. (function (BABYLON) {
  29779. /**
  29780. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29781. */
  29782. var DummyInternalTextureTracker = /** @class */ (function () {
  29783. function DummyInternalTextureTracker() {
  29784. /**
  29785. * Gets or set the previous tracker in the list
  29786. */
  29787. this.previous = null;
  29788. /**
  29789. * Gets or set the next tracker in the list
  29790. */
  29791. this.next = null;
  29792. }
  29793. return DummyInternalTextureTracker;
  29794. }());
  29795. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29796. })(BABYLON || (BABYLON = {}));
  29797. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29798. var BABYLON;
  29799. (function (BABYLON) {
  29800. /**
  29801. * Class used to store data associated with WebGL texture data for the engine
  29802. * This class should not be used directly
  29803. */
  29804. var InternalTexture = /** @class */ (function () {
  29805. /**
  29806. * Creates a new InternalTexture
  29807. * @param engine defines the engine to use
  29808. * @param dataSource defines the type of data that will be used
  29809. */
  29810. function InternalTexture(engine, dataSource) {
  29811. /**
  29812. * Observable called when the texture is loaded
  29813. */
  29814. this.onLoadedObservable = new BABYLON.Observable();
  29815. /**
  29816. * Gets or set the previous tracker in the list
  29817. */
  29818. this.previous = null;
  29819. /**
  29820. * Gets or set the next tracker in the list
  29821. */
  29822. this.next = null;
  29823. // Private
  29824. /** @hidden */
  29825. this._initialSlot = -1;
  29826. /** @hidden */
  29827. this._designatedSlot = -1;
  29828. /** @hidden */
  29829. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29830. /** @hidden */
  29831. this._comparisonFunction = 0;
  29832. /** @hidden */
  29833. this._references = 1;
  29834. this._engine = engine;
  29835. this._dataSource = dataSource;
  29836. this._webGLTexture = engine._createTexture();
  29837. }
  29838. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29839. /**
  29840. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29841. */
  29842. get: function () {
  29843. return this._dataSource;
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. /**
  29849. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29850. */
  29851. InternalTexture.prototype.incrementReferences = function () {
  29852. this._references++;
  29853. };
  29854. /**
  29855. * Change the size of the texture (not the size of the content)
  29856. * @param width defines the new width
  29857. * @param height defines the new height
  29858. * @param depth defines the new depth (1 by default)
  29859. */
  29860. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29861. if (depth === void 0) { depth = 1; }
  29862. this.width = width;
  29863. this.height = height;
  29864. this.depth = depth;
  29865. this.baseWidth = width;
  29866. this.baseHeight = height;
  29867. this.baseDepth = depth;
  29868. this._size = width * height * depth;
  29869. };
  29870. /** @hidden */
  29871. InternalTexture.prototype._rebuild = function () {
  29872. var _this = this;
  29873. var proxy;
  29874. this.isReady = false;
  29875. this._cachedCoordinatesMode = null;
  29876. this._cachedWrapU = null;
  29877. this._cachedWrapV = null;
  29878. this._cachedAnisotropicFilteringLevel = null;
  29879. switch (this._dataSource) {
  29880. case InternalTexture.DATASOURCE_TEMP:
  29881. return;
  29882. case InternalTexture.DATASOURCE_URL:
  29883. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29884. _this.isReady = true;
  29885. }, null, this._buffer, undefined, this.format);
  29886. proxy._swapAndDie(this);
  29887. return;
  29888. case InternalTexture.DATASOURCE_RAW:
  29889. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29890. proxy._swapAndDie(this);
  29891. this.isReady = true;
  29892. return;
  29893. case InternalTexture.DATASOURCE_RAW3D:
  29894. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29895. proxy._swapAndDie(this);
  29896. this.isReady = true;
  29897. return;
  29898. case InternalTexture.DATASOURCE_DYNAMIC:
  29899. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29900. proxy._swapAndDie(this);
  29901. // The engine will make sure to update content so no need to flag it as isReady = true
  29902. return;
  29903. case InternalTexture.DATASOURCE_RENDERTARGET:
  29904. var options = new BABYLON.RenderTargetCreationOptions();
  29905. options.generateDepthBuffer = this._generateDepthBuffer;
  29906. options.generateMipMaps = this.generateMipMaps;
  29907. options.generateStencilBuffer = this._generateStencilBuffer;
  29908. options.samplingMode = this.samplingMode;
  29909. options.type = this.type;
  29910. if (this.isCube) {
  29911. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29912. }
  29913. else {
  29914. var size = {
  29915. width: this.width,
  29916. height: this.height
  29917. };
  29918. proxy = this._engine.createRenderTargetTexture(size, options);
  29919. }
  29920. proxy._swapAndDie(this);
  29921. this.isReady = true;
  29922. return;
  29923. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29924. var depthTextureOptions = {
  29925. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29926. comparisonFunction: this._comparisonFunction,
  29927. generateStencil: this._generateStencilBuffer,
  29928. isCube: this.isCube
  29929. };
  29930. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29931. proxy._swapAndDie(this);
  29932. this.isReady = true;
  29933. return;
  29934. case InternalTexture.DATASOURCE_CUBE:
  29935. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29936. _this.isReady = true;
  29937. }, null, this.format, this._extension);
  29938. proxy._swapAndDie(this);
  29939. return;
  29940. case InternalTexture.DATASOURCE_CUBERAW:
  29941. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29942. proxy._swapAndDie(this);
  29943. this.isReady = true;
  29944. return;
  29945. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29946. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29947. if (proxy) {
  29948. proxy._swapAndDie(_this);
  29949. }
  29950. _this.isReady = true;
  29951. }, null, this.format, this._extension);
  29952. return;
  29953. }
  29954. };
  29955. InternalTexture.prototype._swapAndDie = function (target) {
  29956. target._webGLTexture = this._webGLTexture;
  29957. if (this._framebuffer) {
  29958. target._framebuffer = this._framebuffer;
  29959. }
  29960. if (this._depthStencilBuffer) {
  29961. target._depthStencilBuffer = this._depthStencilBuffer;
  29962. }
  29963. if (this._lodTextureHigh) {
  29964. if (target._lodTextureHigh) {
  29965. target._lodTextureHigh.dispose();
  29966. }
  29967. target._lodTextureHigh = this._lodTextureHigh;
  29968. }
  29969. if (this._lodTextureMid) {
  29970. if (target._lodTextureMid) {
  29971. target._lodTextureMid.dispose();
  29972. }
  29973. target._lodTextureMid = this._lodTextureMid;
  29974. }
  29975. if (this._lodTextureLow) {
  29976. if (target._lodTextureLow) {
  29977. target._lodTextureLow.dispose();
  29978. }
  29979. target._lodTextureLow = this._lodTextureLow;
  29980. }
  29981. var cache = this._engine.getLoadedTexturesCache();
  29982. var index = cache.indexOf(this);
  29983. if (index !== -1) {
  29984. cache.splice(index, 1);
  29985. }
  29986. };
  29987. /**
  29988. * Dispose the current allocated resources
  29989. */
  29990. InternalTexture.prototype.dispose = function () {
  29991. if (!this._webGLTexture) {
  29992. return;
  29993. }
  29994. this._references--;
  29995. if (this._references === 0) {
  29996. this._engine._releaseTexture(this);
  29997. this._webGLTexture = null;
  29998. this.previous = null;
  29999. this.next = null;
  30000. }
  30001. };
  30002. /**
  30003. * The source of the texture data is unknown
  30004. */
  30005. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30006. /**
  30007. * Texture data comes from an URL
  30008. */
  30009. InternalTexture.DATASOURCE_URL = 1;
  30010. /**
  30011. * Texture data is only used for temporary storage
  30012. */
  30013. InternalTexture.DATASOURCE_TEMP = 2;
  30014. /**
  30015. * Texture data comes from raw data (ArrayBuffer)
  30016. */
  30017. InternalTexture.DATASOURCE_RAW = 3;
  30018. /**
  30019. * Texture content is dynamic (video or dynamic texture)
  30020. */
  30021. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30022. /**
  30023. * Texture content is generated by rendering to it
  30024. */
  30025. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30026. /**
  30027. * Texture content is part of a multi render target process
  30028. */
  30029. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30030. /**
  30031. * Texture data comes from a cube data file
  30032. */
  30033. InternalTexture.DATASOURCE_CUBE = 7;
  30034. /**
  30035. * Texture data comes from a raw cube data
  30036. */
  30037. InternalTexture.DATASOURCE_CUBERAW = 8;
  30038. /**
  30039. * Texture data come from a prefiltered cube data file
  30040. */
  30041. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30042. /**
  30043. * Texture content is raw 3D data
  30044. */
  30045. InternalTexture.DATASOURCE_RAW3D = 10;
  30046. /**
  30047. * Texture content is a depth texture
  30048. */
  30049. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30050. return InternalTexture;
  30051. }());
  30052. BABYLON.InternalTexture = InternalTexture;
  30053. })(BABYLON || (BABYLON = {}));
  30054. //# sourceMappingURL=babylon.internalTexture.js.map
  30055. var BABYLON;
  30056. (function (BABYLON) {
  30057. var BaseTexture = /** @class */ (function () {
  30058. function BaseTexture(scene) {
  30059. this._hasAlpha = false;
  30060. this.getAlphaFromRGB = false;
  30061. this.level = 1;
  30062. this.coordinatesIndex = 0;
  30063. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30064. /**
  30065. * | Value | Type | Description |
  30066. * | ----- | ------------------ | ----------- |
  30067. * | 0 | CLAMP_ADDRESSMODE | |
  30068. * | 1 | WRAP_ADDRESSMODE | |
  30069. * | 2 | MIRROR_ADDRESSMODE | |
  30070. */
  30071. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30072. /**
  30073. * | Value | Type | Description |
  30074. * | ----- | ------------------ | ----------- |
  30075. * | 0 | CLAMP_ADDRESSMODE | |
  30076. * | 1 | WRAP_ADDRESSMODE | |
  30077. * | 2 | MIRROR_ADDRESSMODE | |
  30078. */
  30079. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30080. /**
  30081. * | Value | Type | Description |
  30082. * | ----- | ------------------ | ----------- |
  30083. * | 0 | CLAMP_ADDRESSMODE | |
  30084. * | 1 | WRAP_ADDRESSMODE | |
  30085. * | 2 | MIRROR_ADDRESSMODE | |
  30086. */
  30087. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30088. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30089. this.isCube = false;
  30090. this.is3D = false;
  30091. this.gammaSpace = true;
  30092. this.invertZ = false;
  30093. this.lodLevelInAlpha = false;
  30094. this.lodGenerationOffset = 0.0;
  30095. this.lodGenerationScale = 0.8;
  30096. this.isRenderTarget = false;
  30097. this.animations = new Array();
  30098. /**
  30099. * An event triggered when the texture is disposed.
  30100. */
  30101. this.onDisposeObservable = new BABYLON.Observable();
  30102. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30103. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30104. if (this._scene) {
  30105. this._scene.textures.push(this);
  30106. }
  30107. this._uid = null;
  30108. }
  30109. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30110. get: function () {
  30111. return this._hasAlpha;
  30112. },
  30113. set: function (value) {
  30114. if (this._hasAlpha === value) {
  30115. return;
  30116. }
  30117. this._hasAlpha = value;
  30118. if (this._scene) {
  30119. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30120. }
  30121. },
  30122. enumerable: true,
  30123. configurable: true
  30124. });
  30125. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30126. get: function () {
  30127. return this._coordinatesMode;
  30128. },
  30129. /**
  30130. * How a texture is mapped.
  30131. *
  30132. * | Value | Type | Description |
  30133. * | ----- | ----------------------------------- | ----------- |
  30134. * | 0 | EXPLICIT_MODE | |
  30135. * | 1 | SPHERICAL_MODE | |
  30136. * | 2 | PLANAR_MODE | |
  30137. * | 3 | CUBIC_MODE | |
  30138. * | 4 | PROJECTION_MODE | |
  30139. * | 5 | SKYBOX_MODE | |
  30140. * | 6 | INVCUBIC_MODE | |
  30141. * | 7 | EQUIRECTANGULAR_MODE | |
  30142. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30143. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30144. */
  30145. set: function (value) {
  30146. if (this._coordinatesMode === value) {
  30147. return;
  30148. }
  30149. this._coordinatesMode = value;
  30150. if (this._scene) {
  30151. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30152. }
  30153. },
  30154. enumerable: true,
  30155. configurable: true
  30156. });
  30157. Object.defineProperty(BaseTexture.prototype, "uid", {
  30158. get: function () {
  30159. if (!this._uid) {
  30160. this._uid = BABYLON.Tools.RandomId();
  30161. }
  30162. return this._uid;
  30163. },
  30164. enumerable: true,
  30165. configurable: true
  30166. });
  30167. BaseTexture.prototype.toString = function () {
  30168. return this.name;
  30169. };
  30170. BaseTexture.prototype.getClassName = function () {
  30171. return "BaseTexture";
  30172. };
  30173. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30174. set: function (callback) {
  30175. if (this._onDisposeObserver) {
  30176. this.onDisposeObservable.remove(this._onDisposeObserver);
  30177. }
  30178. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30179. },
  30180. enumerable: true,
  30181. configurable: true
  30182. });
  30183. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30184. get: function () {
  30185. return true;
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. BaseTexture.prototype.getScene = function () {
  30191. return this._scene;
  30192. };
  30193. BaseTexture.prototype.getTextureMatrix = function () {
  30194. return BABYLON.Matrix.IdentityReadOnly;
  30195. };
  30196. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30197. return BABYLON.Matrix.IdentityReadOnly;
  30198. };
  30199. BaseTexture.prototype.getInternalTexture = function () {
  30200. return this._texture;
  30201. };
  30202. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30203. return !this.isBlocking || this.isReady();
  30204. };
  30205. BaseTexture.prototype.isReady = function () {
  30206. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30207. this.delayLoad();
  30208. return false;
  30209. }
  30210. if (this._texture) {
  30211. return this._texture.isReady;
  30212. }
  30213. return false;
  30214. };
  30215. BaseTexture.prototype.getSize = function () {
  30216. if (this._texture && this._texture.width) {
  30217. return new BABYLON.Size(this._texture.width, this._texture.height);
  30218. }
  30219. if (this._texture && this._texture._size) {
  30220. return new BABYLON.Size(this._texture._size, this._texture._size);
  30221. }
  30222. return BABYLON.Size.Zero();
  30223. };
  30224. BaseTexture.prototype.getBaseSize = function () {
  30225. if (!this.isReady() || !this._texture)
  30226. return BABYLON.Size.Zero();
  30227. if (this._texture._size) {
  30228. return new BABYLON.Size(this._texture._size, this._texture._size);
  30229. }
  30230. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30231. };
  30232. BaseTexture.prototype.scale = function (ratio) {
  30233. };
  30234. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30235. get: function () {
  30236. return false;
  30237. },
  30238. enumerable: true,
  30239. configurable: true
  30240. });
  30241. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30242. if (!this._scene) {
  30243. return null;
  30244. }
  30245. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30246. for (var index = 0; index < texturesCache.length; index++) {
  30247. var texturesCacheEntry = texturesCache[index];
  30248. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30249. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30250. texturesCacheEntry.incrementReferences();
  30251. return texturesCacheEntry;
  30252. }
  30253. }
  30254. }
  30255. return null;
  30256. };
  30257. BaseTexture.prototype._rebuild = function () {
  30258. };
  30259. BaseTexture.prototype.delayLoad = function () {
  30260. };
  30261. BaseTexture.prototype.clone = function () {
  30262. return null;
  30263. };
  30264. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30265. get: function () {
  30266. if (!this._texture) {
  30267. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30268. }
  30269. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30270. },
  30271. enumerable: true,
  30272. configurable: true
  30273. });
  30274. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30275. get: function () {
  30276. if (!this._texture) {
  30277. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30278. }
  30279. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30280. },
  30281. enumerable: true,
  30282. configurable: true
  30283. });
  30284. BaseTexture.prototype.readPixels = function (faceIndex) {
  30285. if (faceIndex === void 0) { faceIndex = 0; }
  30286. if (!this._texture) {
  30287. return null;
  30288. }
  30289. var size = this.getSize();
  30290. var scene = this.getScene();
  30291. if (!scene) {
  30292. return null;
  30293. }
  30294. var engine = scene.getEngine();
  30295. if (this._texture.isCube) {
  30296. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30297. }
  30298. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30299. };
  30300. BaseTexture.prototype.releaseInternalTexture = function () {
  30301. if (this._texture) {
  30302. this._texture.dispose();
  30303. this._texture = null;
  30304. }
  30305. };
  30306. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30307. get: function () {
  30308. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30309. return null;
  30310. }
  30311. if (!this._texture._sphericalPolynomial) {
  30312. this._texture._sphericalPolynomial =
  30313. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30314. }
  30315. return this._texture._sphericalPolynomial;
  30316. },
  30317. set: function (value) {
  30318. if (this._texture) {
  30319. this._texture._sphericalPolynomial = value;
  30320. }
  30321. },
  30322. enumerable: true,
  30323. configurable: true
  30324. });
  30325. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30326. get: function () {
  30327. if (this._texture) {
  30328. return this._texture._lodTextureHigh;
  30329. }
  30330. return null;
  30331. },
  30332. enumerable: true,
  30333. configurable: true
  30334. });
  30335. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30336. get: function () {
  30337. if (this._texture) {
  30338. return this._texture._lodTextureMid;
  30339. }
  30340. return null;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30346. get: function () {
  30347. if (this._texture) {
  30348. return this._texture._lodTextureLow;
  30349. }
  30350. return null;
  30351. },
  30352. enumerable: true,
  30353. configurable: true
  30354. });
  30355. BaseTexture.prototype.dispose = function () {
  30356. if (!this._scene) {
  30357. return;
  30358. }
  30359. // Animations
  30360. this._scene.stopAnimation(this);
  30361. // Remove from scene
  30362. this._scene._removePendingData(this);
  30363. var index = this._scene.textures.indexOf(this);
  30364. if (index >= 0) {
  30365. this._scene.textures.splice(index, 1);
  30366. }
  30367. if (this._texture === undefined) {
  30368. return;
  30369. }
  30370. // Release
  30371. this.releaseInternalTexture();
  30372. // Callback
  30373. this.onDisposeObservable.notifyObservers(this);
  30374. this.onDisposeObservable.clear();
  30375. };
  30376. BaseTexture.prototype.serialize = function () {
  30377. if (!this.name) {
  30378. return null;
  30379. }
  30380. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30381. // Animations
  30382. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30383. return serializationObject;
  30384. };
  30385. BaseTexture.WhenAllReady = function (textures, callback) {
  30386. var numRemaining = textures.length;
  30387. if (numRemaining === 0) {
  30388. callback();
  30389. return;
  30390. }
  30391. var _loop_1 = function () {
  30392. texture = textures[i];
  30393. if (texture.isReady()) {
  30394. if (--numRemaining === 0) {
  30395. callback();
  30396. }
  30397. }
  30398. else {
  30399. onLoadObservable = texture.onLoadObservable;
  30400. var onLoadCallback_1 = function () {
  30401. onLoadObservable.removeCallback(onLoadCallback_1);
  30402. if (--numRemaining === 0) {
  30403. callback();
  30404. }
  30405. };
  30406. onLoadObservable.add(onLoadCallback_1);
  30407. }
  30408. };
  30409. var texture, onLoadObservable;
  30410. for (var i = 0; i < textures.length; i++) {
  30411. _loop_1();
  30412. }
  30413. };
  30414. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "name", void 0);
  30418. __decorate([
  30419. BABYLON.serialize("hasAlpha")
  30420. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30421. __decorate([
  30422. BABYLON.serialize()
  30423. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30424. __decorate([
  30425. BABYLON.serialize()
  30426. ], BaseTexture.prototype, "level", void 0);
  30427. __decorate([
  30428. BABYLON.serialize()
  30429. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30430. __decorate([
  30431. BABYLON.serialize("coordinatesMode")
  30432. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30433. __decorate([
  30434. BABYLON.serialize()
  30435. ], BaseTexture.prototype, "wrapU", void 0);
  30436. __decorate([
  30437. BABYLON.serialize()
  30438. ], BaseTexture.prototype, "wrapV", void 0);
  30439. __decorate([
  30440. BABYLON.serialize()
  30441. ], BaseTexture.prototype, "wrapR", void 0);
  30442. __decorate([
  30443. BABYLON.serialize()
  30444. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30445. __decorate([
  30446. BABYLON.serialize()
  30447. ], BaseTexture.prototype, "isCube", void 0);
  30448. __decorate([
  30449. BABYLON.serialize()
  30450. ], BaseTexture.prototype, "is3D", void 0);
  30451. __decorate([
  30452. BABYLON.serialize()
  30453. ], BaseTexture.prototype, "gammaSpace", void 0);
  30454. __decorate([
  30455. BABYLON.serialize()
  30456. ], BaseTexture.prototype, "invertZ", void 0);
  30457. __decorate([
  30458. BABYLON.serialize()
  30459. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30460. __decorate([
  30461. BABYLON.serialize()
  30462. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30463. __decorate([
  30464. BABYLON.serialize()
  30465. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30466. __decorate([
  30467. BABYLON.serialize()
  30468. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30469. return BaseTexture;
  30470. }());
  30471. BABYLON.BaseTexture = BaseTexture;
  30472. })(BABYLON || (BABYLON = {}));
  30473. //# sourceMappingURL=babylon.baseTexture.js.map
  30474. var BABYLON;
  30475. (function (BABYLON) {
  30476. var Texture = /** @class */ (function (_super) {
  30477. __extends(Texture, _super);
  30478. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30479. if (noMipmap === void 0) { noMipmap = false; }
  30480. if (invertY === void 0) { invertY = true; }
  30481. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30482. if (onLoad === void 0) { onLoad = null; }
  30483. if (onError === void 0) { onError = null; }
  30484. if (buffer === void 0) { buffer = null; }
  30485. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30486. var _this = _super.call(this, scene) || this;
  30487. _this.uOffset = 0;
  30488. _this.vOffset = 0;
  30489. _this.uScale = 1.0;
  30490. _this.vScale = 1.0;
  30491. _this.uAng = 0;
  30492. _this.vAng = 0;
  30493. _this.wAng = 0;
  30494. /**
  30495. * Defines the center of rotation (U)
  30496. */
  30497. _this.uRotationCenter = 0.5;
  30498. /**
  30499. * Defines the center of rotation (V)
  30500. */
  30501. _this.vRotationCenter = 0.5;
  30502. /**
  30503. * Defines the center of rotation (W)
  30504. */
  30505. _this.wRotationCenter = 0.5;
  30506. _this._isBlocking = true;
  30507. _this.name = url || "";
  30508. _this.url = url;
  30509. _this._noMipmap = noMipmap;
  30510. _this._invertY = invertY;
  30511. _this._samplingMode = samplingMode;
  30512. _this._buffer = buffer;
  30513. _this._deleteBuffer = deleteBuffer;
  30514. if (format) {
  30515. _this._format = format;
  30516. }
  30517. scene = _this.getScene();
  30518. if (!scene) {
  30519. return _this;
  30520. }
  30521. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30522. var load = function () {
  30523. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30524. _this.onLoadObservable.notifyObservers(_this);
  30525. }
  30526. if (onLoad) {
  30527. onLoad();
  30528. }
  30529. if (!_this.isBlocking && scene) {
  30530. scene.resetCachedMaterial();
  30531. }
  30532. };
  30533. if (!_this.url) {
  30534. _this._delayedOnLoad = load;
  30535. _this._delayedOnError = onError;
  30536. return _this;
  30537. }
  30538. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30539. if (!_this._texture) {
  30540. if (!scene.useDelayedTextureLoading) {
  30541. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30542. if (deleteBuffer) {
  30543. delete _this._buffer;
  30544. }
  30545. }
  30546. else {
  30547. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30548. _this._delayedOnLoad = load;
  30549. _this._delayedOnError = onError;
  30550. }
  30551. }
  30552. else {
  30553. if (_this._texture.isReady) {
  30554. BABYLON.Tools.SetImmediate(function () { return load(); });
  30555. }
  30556. else {
  30557. _this._texture.onLoadedObservable.add(load);
  30558. }
  30559. }
  30560. return _this;
  30561. }
  30562. Object.defineProperty(Texture.prototype, "noMipmap", {
  30563. get: function () {
  30564. return this._noMipmap;
  30565. },
  30566. enumerable: true,
  30567. configurable: true
  30568. });
  30569. Object.defineProperty(Texture.prototype, "isBlocking", {
  30570. get: function () {
  30571. return this._isBlocking;
  30572. },
  30573. set: function (value) {
  30574. this._isBlocking = value;
  30575. },
  30576. enumerable: true,
  30577. configurable: true
  30578. });
  30579. Object.defineProperty(Texture.prototype, "samplingMode", {
  30580. get: function () {
  30581. return this._samplingMode;
  30582. },
  30583. enumerable: true,
  30584. configurable: true
  30585. });
  30586. Texture.prototype.updateURL = function (url) {
  30587. this.url = url;
  30588. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30589. this.delayLoad();
  30590. };
  30591. Texture.prototype.delayLoad = function () {
  30592. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30593. return;
  30594. }
  30595. var scene = this.getScene();
  30596. if (!scene) {
  30597. return;
  30598. }
  30599. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30600. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30601. if (!this._texture) {
  30602. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30603. if (this._deleteBuffer) {
  30604. delete this._buffer;
  30605. }
  30606. }
  30607. else {
  30608. if (this._delayedOnLoad) {
  30609. if (this._texture.isReady) {
  30610. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30611. }
  30612. else {
  30613. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30614. }
  30615. }
  30616. }
  30617. this._delayedOnLoad = null;
  30618. this._delayedOnError = null;
  30619. };
  30620. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30621. if (!this._texture) {
  30622. return;
  30623. }
  30624. var scene = this.getScene();
  30625. if (!scene) {
  30626. return;
  30627. }
  30628. this._samplingMode = samplingMode;
  30629. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30630. };
  30631. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30632. x *= this.uScale;
  30633. y *= this.vScale;
  30634. x -= this.uRotationCenter * this.uScale;
  30635. y -= this.vRotationCenter * this.vScale;
  30636. z -= this.wRotationCenter;
  30637. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30638. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  30639. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  30640. t.z += this.wRotationCenter;
  30641. };
  30642. Texture.prototype.getTextureMatrix = function () {
  30643. var _this = this;
  30644. if (this.uOffset === this._cachedUOffset &&
  30645. this.vOffset === this._cachedVOffset &&
  30646. this.uScale === this._cachedUScale &&
  30647. this.vScale === this._cachedVScale &&
  30648. this.uAng === this._cachedUAng &&
  30649. this.vAng === this._cachedVAng &&
  30650. this.wAng === this._cachedWAng) {
  30651. return this._cachedTextureMatrix;
  30652. }
  30653. this._cachedUOffset = this.uOffset;
  30654. this._cachedVOffset = this.vOffset;
  30655. this._cachedUScale = this.uScale;
  30656. this._cachedVScale = this.vScale;
  30657. this._cachedUAng = this.uAng;
  30658. this._cachedVAng = this.vAng;
  30659. this._cachedWAng = this.wAng;
  30660. if (!this._cachedTextureMatrix) {
  30661. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30662. this._rowGenerationMatrix = new BABYLON.Matrix();
  30663. this._t0 = BABYLON.Vector3.Zero();
  30664. this._t1 = BABYLON.Vector3.Zero();
  30665. this._t2 = BABYLON.Vector3.Zero();
  30666. }
  30667. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30668. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30669. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30670. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30671. this._t1.subtractInPlace(this._t0);
  30672. this._t2.subtractInPlace(this._t0);
  30673. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30674. this._cachedTextureMatrix.m[0] = this._t1.x;
  30675. this._cachedTextureMatrix.m[1] = this._t1.y;
  30676. this._cachedTextureMatrix.m[2] = this._t1.z;
  30677. this._cachedTextureMatrix.m[4] = this._t2.x;
  30678. this._cachedTextureMatrix.m[5] = this._t2.y;
  30679. this._cachedTextureMatrix.m[6] = this._t2.z;
  30680. this._cachedTextureMatrix.m[8] = this._t0.x;
  30681. this._cachedTextureMatrix.m[9] = this._t0.y;
  30682. this._cachedTextureMatrix.m[10] = this._t0.z;
  30683. var scene = this.getScene();
  30684. if (!scene) {
  30685. return this._cachedTextureMatrix;
  30686. }
  30687. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30688. return mat.hasTexture(_this);
  30689. });
  30690. return this._cachedTextureMatrix;
  30691. };
  30692. Texture.prototype.getReflectionTextureMatrix = function () {
  30693. var _this = this;
  30694. var scene = this.getScene();
  30695. if (!scene) {
  30696. return this._cachedTextureMatrix;
  30697. }
  30698. if (this.uOffset === this._cachedUOffset &&
  30699. this.vOffset === this._cachedVOffset &&
  30700. this.uScale === this._cachedUScale &&
  30701. this.vScale === this._cachedVScale &&
  30702. this.coordinatesMode === this._cachedCoordinatesMode) {
  30703. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30704. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30705. return this._cachedTextureMatrix;
  30706. }
  30707. }
  30708. else {
  30709. return this._cachedTextureMatrix;
  30710. }
  30711. }
  30712. if (!this._cachedTextureMatrix) {
  30713. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30714. }
  30715. if (!this._projectionModeMatrix) {
  30716. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30717. }
  30718. this._cachedUOffset = this.uOffset;
  30719. this._cachedVOffset = this.vOffset;
  30720. this._cachedUScale = this.uScale;
  30721. this._cachedVScale = this.vScale;
  30722. this._cachedCoordinatesMode = this.coordinatesMode;
  30723. switch (this.coordinatesMode) {
  30724. case Texture.PLANAR_MODE:
  30725. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30726. this._cachedTextureMatrix[0] = this.uScale;
  30727. this._cachedTextureMatrix[5] = this.vScale;
  30728. this._cachedTextureMatrix[12] = this.uOffset;
  30729. this._cachedTextureMatrix[13] = this.vOffset;
  30730. break;
  30731. case Texture.PROJECTION_MODE:
  30732. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30733. this._projectionModeMatrix.m[0] = 0.5;
  30734. this._projectionModeMatrix.m[5] = -0.5;
  30735. this._projectionModeMatrix.m[10] = 0.0;
  30736. this._projectionModeMatrix.m[12] = 0.5;
  30737. this._projectionModeMatrix.m[13] = 0.5;
  30738. this._projectionModeMatrix.m[14] = 1.0;
  30739. this._projectionModeMatrix.m[15] = 1.0;
  30740. var projectionMatrix = scene.getProjectionMatrix();
  30741. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30742. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30743. break;
  30744. default:
  30745. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30746. break;
  30747. }
  30748. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30749. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30750. });
  30751. return this._cachedTextureMatrix;
  30752. };
  30753. Texture.prototype.clone = function () {
  30754. var _this = this;
  30755. return BABYLON.SerializationHelper.Clone(function () {
  30756. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30757. }, this);
  30758. };
  30759. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30760. get: function () {
  30761. if (!this._onLoadObservable) {
  30762. this._onLoadObservable = new BABYLON.Observable();
  30763. }
  30764. return this._onLoadObservable;
  30765. },
  30766. enumerable: true,
  30767. configurable: true
  30768. });
  30769. Texture.prototype.serialize = function () {
  30770. var serializationObject = _super.prototype.serialize.call(this);
  30771. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30772. serializationObject.base64String = this._buffer;
  30773. serializationObject.name = serializationObject.name.replace("data:", "");
  30774. }
  30775. serializationObject.invertY = this._invertY;
  30776. serializationObject.samplingMode = this.samplingMode;
  30777. return serializationObject;
  30778. };
  30779. Texture.prototype.getClassName = function () {
  30780. return "Texture";
  30781. };
  30782. Texture.prototype.dispose = function () {
  30783. _super.prototype.dispose.call(this);
  30784. if (this.onLoadObservable) {
  30785. this.onLoadObservable.clear();
  30786. this._onLoadObservable = null;
  30787. }
  30788. this._delayedOnLoad = null;
  30789. this._delayedOnError = null;
  30790. };
  30791. // Statics
  30792. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30793. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30794. if (onLoad === void 0) { onLoad = null; }
  30795. if (onError === void 0) { onError = null; }
  30796. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30797. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30798. };
  30799. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30800. if (parsedTexture.customType) {
  30801. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30802. // Update Sampling Mode
  30803. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30804. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30805. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30806. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30807. }
  30808. }
  30809. return parsedCustomTexture;
  30810. }
  30811. if (parsedTexture.isCube) {
  30812. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30813. }
  30814. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30815. return null;
  30816. }
  30817. var texture = BABYLON.SerializationHelper.Parse(function () {
  30818. var generateMipMaps = true;
  30819. if (parsedTexture.noMipmap) {
  30820. generateMipMaps = false;
  30821. }
  30822. if (parsedTexture.mirrorPlane) {
  30823. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30824. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30825. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30826. return mirrorTexture;
  30827. }
  30828. else if (parsedTexture.isRenderTarget) {
  30829. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30830. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30831. return renderTargetTexture;
  30832. }
  30833. else {
  30834. var texture;
  30835. if (parsedTexture.base64String) {
  30836. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30837. }
  30838. else {
  30839. var url = rootUrl + parsedTexture.name;
  30840. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30841. url = parsedTexture.url;
  30842. }
  30843. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30844. }
  30845. return texture;
  30846. }
  30847. }, parsedTexture, scene);
  30848. // Update Sampling Mode
  30849. if (parsedTexture.samplingMode) {
  30850. var sampling = parsedTexture.samplingMode;
  30851. if (texture._samplingMode !== sampling) {
  30852. texture.updateSamplingMode(sampling);
  30853. }
  30854. }
  30855. // Animations
  30856. if (parsedTexture.animations) {
  30857. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30858. var parsedAnimation = parsedTexture.animations[animationIndex];
  30859. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30860. }
  30861. }
  30862. return texture;
  30863. };
  30864. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30865. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30866. if (noMipmap === void 0) { noMipmap = false; }
  30867. if (invertY === void 0) { invertY = true; }
  30868. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30869. if (onLoad === void 0) { onLoad = null; }
  30870. if (onError === void 0) { onError = null; }
  30871. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30872. if (name.substr(0, 5) !== "data:") {
  30873. name = "data:" + name;
  30874. }
  30875. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30876. };
  30877. // Constants
  30878. Texture.NEAREST_SAMPLINGMODE = 1;
  30879. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30880. Texture.BILINEAR_SAMPLINGMODE = 2;
  30881. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30882. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30883. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30884. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30885. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30886. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30887. Texture.NEAREST_LINEAR = 7;
  30888. Texture.NEAREST_NEAREST = 8;
  30889. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30890. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30891. Texture.LINEAR_LINEAR = 11;
  30892. Texture.LINEAR_NEAREST = 12;
  30893. Texture.EXPLICIT_MODE = 0;
  30894. Texture.SPHERICAL_MODE = 1;
  30895. Texture.PLANAR_MODE = 2;
  30896. Texture.CUBIC_MODE = 3;
  30897. Texture.PROJECTION_MODE = 4;
  30898. Texture.SKYBOX_MODE = 5;
  30899. Texture.INVCUBIC_MODE = 6;
  30900. Texture.EQUIRECTANGULAR_MODE = 7;
  30901. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30902. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30903. Texture.CLAMP_ADDRESSMODE = 0;
  30904. Texture.WRAP_ADDRESSMODE = 1;
  30905. Texture.MIRROR_ADDRESSMODE = 2;
  30906. /**
  30907. * 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
  30908. */
  30909. Texture.UseSerializedUrlIfAny = false;
  30910. __decorate([
  30911. BABYLON.serialize()
  30912. ], Texture.prototype, "url", void 0);
  30913. __decorate([
  30914. BABYLON.serialize()
  30915. ], Texture.prototype, "uOffset", void 0);
  30916. __decorate([
  30917. BABYLON.serialize()
  30918. ], Texture.prototype, "vOffset", void 0);
  30919. __decorate([
  30920. BABYLON.serialize()
  30921. ], Texture.prototype, "uScale", void 0);
  30922. __decorate([
  30923. BABYLON.serialize()
  30924. ], Texture.prototype, "vScale", void 0);
  30925. __decorate([
  30926. BABYLON.serialize()
  30927. ], Texture.prototype, "uAng", void 0);
  30928. __decorate([
  30929. BABYLON.serialize()
  30930. ], Texture.prototype, "vAng", void 0);
  30931. __decorate([
  30932. BABYLON.serialize()
  30933. ], Texture.prototype, "wAng", void 0);
  30934. __decorate([
  30935. BABYLON.serialize()
  30936. ], Texture.prototype, "uRotationCenter", void 0);
  30937. __decorate([
  30938. BABYLON.serialize()
  30939. ], Texture.prototype, "vRotationCenter", void 0);
  30940. __decorate([
  30941. BABYLON.serialize()
  30942. ], Texture.prototype, "wRotationCenter", void 0);
  30943. __decorate([
  30944. BABYLON.serialize()
  30945. ], Texture.prototype, "isBlocking", null);
  30946. return Texture;
  30947. }(BABYLON.BaseTexture));
  30948. BABYLON.Texture = Texture;
  30949. })(BABYLON || (BABYLON = {}));
  30950. //# sourceMappingURL=babylon.texture.js.map
  30951. var BABYLON;
  30952. (function (BABYLON) {
  30953. /**
  30954. * @hidden
  30955. **/
  30956. var _InstancesBatch = /** @class */ (function () {
  30957. function _InstancesBatch() {
  30958. this.mustReturn = false;
  30959. this.visibleInstances = new Array();
  30960. this.renderSelf = new Array();
  30961. }
  30962. return _InstancesBatch;
  30963. }());
  30964. BABYLON._InstancesBatch = _InstancesBatch;
  30965. var Mesh = /** @class */ (function (_super) {
  30966. __extends(Mesh, _super);
  30967. /**
  30968. * @constructor
  30969. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30970. * @param {Scene} scene The scene to add this mesh to.
  30971. * @param {Node} parent The parent of this mesh, if it has one
  30972. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30973. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30974. * When false, achieved by calling a clone(), also passing False.
  30975. * This will make creation of children, recursive.
  30976. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30977. */
  30978. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30979. if (scene === void 0) { scene = null; }
  30980. if (parent === void 0) { parent = null; }
  30981. if (source === void 0) { source = null; }
  30982. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30983. var _this = _super.call(this, name, scene) || this;
  30984. // Events
  30985. /**
  30986. * An event triggered before rendering the mesh
  30987. */
  30988. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30989. /**
  30990. * An event triggered after rendering the mesh
  30991. */
  30992. _this.onAfterRenderObservable = new BABYLON.Observable();
  30993. /**
  30994. * An event triggered before drawing the mesh
  30995. */
  30996. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30997. // Members
  30998. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30999. _this.instances = new Array();
  31000. _this._LODLevels = new Array();
  31001. _this._visibleInstances = {};
  31002. _this._renderIdForInstances = new Array();
  31003. _this._batchCache = new _InstancesBatch();
  31004. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31005. // Use by builder only to know what orientation were the mesh build in.
  31006. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31007. _this.overrideMaterialSideOrientation = null;
  31008. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31009. // Will be used to save a source mesh reference, If any
  31010. _this._source = null;
  31011. scene = _this.getScene();
  31012. if (source) {
  31013. // Source mesh
  31014. _this._source = source;
  31015. // Geometry
  31016. if (source._geometry) {
  31017. source._geometry.applyToMesh(_this);
  31018. }
  31019. // Deep copy
  31020. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31021. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  31022. // Metadata
  31023. if (source.metadata && source.metadata.clone) {
  31024. _this.metadata = source.metadata.clone();
  31025. }
  31026. else {
  31027. _this.metadata = source.metadata;
  31028. }
  31029. // Tags
  31030. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31031. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31032. }
  31033. // Parent
  31034. _this.parent = source.parent;
  31035. // Pivot
  31036. _this.setPivotMatrix(source.getPivotMatrix());
  31037. _this.id = name + "." + source.id;
  31038. // Material
  31039. _this.material = source.material;
  31040. var index;
  31041. if (!doNotCloneChildren) {
  31042. // Children
  31043. var directDescendants = source.getDescendants(true);
  31044. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31045. var child = directDescendants[index_1];
  31046. if (child.clone) {
  31047. child.clone(name + "." + child.name, _this);
  31048. }
  31049. }
  31050. }
  31051. // Physics clone
  31052. var physicsEngine = _this.getScene().getPhysicsEngine();
  31053. if (clonePhysicsImpostor && physicsEngine) {
  31054. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31055. if (impostor) {
  31056. _this.physicsImpostor = impostor.clone(_this);
  31057. }
  31058. }
  31059. // Particles
  31060. for (index = 0; index < scene.particleSystems.length; index++) {
  31061. var system = scene.particleSystems[index];
  31062. if (system.emitter === source) {
  31063. system.clone(system.name, _this);
  31064. }
  31065. }
  31066. _this.computeWorldMatrix(true);
  31067. }
  31068. // Parent
  31069. if (parent !== null) {
  31070. _this.parent = parent;
  31071. }
  31072. return _this;
  31073. }
  31074. Object.defineProperty(Mesh, "FRONTSIDE", {
  31075. /**
  31076. * Mesh side orientation : usually the external or front surface
  31077. */
  31078. get: function () {
  31079. return Mesh._FRONTSIDE;
  31080. },
  31081. enumerable: true,
  31082. configurable: true
  31083. });
  31084. Object.defineProperty(Mesh, "BACKSIDE", {
  31085. /**
  31086. * Mesh side orientation : usually the internal or back surface
  31087. */
  31088. get: function () {
  31089. return Mesh._BACKSIDE;
  31090. },
  31091. enumerable: true,
  31092. configurable: true
  31093. });
  31094. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31095. /**
  31096. * Mesh side orientation : both internal and external or front and back surfaces
  31097. */
  31098. get: function () {
  31099. return Mesh._DOUBLESIDE;
  31100. },
  31101. enumerable: true,
  31102. configurable: true
  31103. });
  31104. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31105. /**
  31106. * Mesh side orientation : by default, `FRONTSIDE`
  31107. */
  31108. get: function () {
  31109. return Mesh._DEFAULTSIDE;
  31110. },
  31111. enumerable: true,
  31112. configurable: true
  31113. });
  31114. Object.defineProperty(Mesh, "NO_CAP", {
  31115. /**
  31116. * Mesh cap setting : no cap
  31117. */
  31118. get: function () {
  31119. return Mesh._NO_CAP;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(Mesh, "CAP_START", {
  31125. /**
  31126. * Mesh cap setting : one cap at the beginning of the mesh
  31127. */
  31128. get: function () {
  31129. return Mesh._CAP_START;
  31130. },
  31131. enumerable: true,
  31132. configurable: true
  31133. });
  31134. Object.defineProperty(Mesh, "CAP_END", {
  31135. /**
  31136. * Mesh cap setting : one cap at the end of the mesh
  31137. */
  31138. get: function () {
  31139. return Mesh._CAP_END;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(Mesh, "CAP_ALL", {
  31145. /**
  31146. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31147. */
  31148. get: function () {
  31149. return Mesh._CAP_ALL;
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31155. set: function (callback) {
  31156. if (this._onBeforeDrawObserver) {
  31157. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31158. }
  31159. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31160. },
  31161. enumerable: true,
  31162. configurable: true
  31163. });
  31164. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31165. get: function () {
  31166. return this._morphTargetManager;
  31167. },
  31168. set: function (value) {
  31169. if (this._morphTargetManager === value) {
  31170. return;
  31171. }
  31172. this._morphTargetManager = value;
  31173. this._syncGeometryWithMorphTargetManager();
  31174. },
  31175. enumerable: true,
  31176. configurable: true
  31177. });
  31178. Object.defineProperty(Mesh.prototype, "source", {
  31179. get: function () {
  31180. return this._source;
  31181. },
  31182. enumerable: true,
  31183. configurable: true
  31184. });
  31185. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31186. get: function () {
  31187. return this._unIndexed;
  31188. },
  31189. set: function (value) {
  31190. if (this._unIndexed !== value) {
  31191. this._unIndexed = value;
  31192. this._markSubMeshesAsAttributesDirty();
  31193. }
  31194. },
  31195. enumerable: true,
  31196. configurable: true
  31197. });
  31198. // Methods
  31199. /**
  31200. * Returns the string "Mesh".
  31201. */
  31202. Mesh.prototype.getClassName = function () {
  31203. return "Mesh";
  31204. };
  31205. /**
  31206. * Returns a string.
  31207. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31208. */
  31209. Mesh.prototype.toString = function (fullDetails) {
  31210. var ret = _super.prototype.toString.call(this, fullDetails);
  31211. ret += ", n vertices: " + this.getTotalVertices();
  31212. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31213. if (this.animations) {
  31214. for (var i = 0; i < this.animations.length; i++) {
  31215. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31216. }
  31217. }
  31218. if (fullDetails) {
  31219. if (this._geometry) {
  31220. var ib = this.getIndices();
  31221. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31222. if (vb && ib) {
  31223. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31224. }
  31225. }
  31226. else {
  31227. ret += ", flat shading: UNKNOWN";
  31228. }
  31229. }
  31230. return ret;
  31231. };
  31232. Mesh.prototype._unBindEffect = function () {
  31233. _super.prototype._unBindEffect.call(this);
  31234. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31235. var instance = _a[_i];
  31236. instance._unBindEffect();
  31237. }
  31238. };
  31239. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31240. /**
  31241. * True if the mesh has some Levels Of Details (LOD).
  31242. * Returns a boolean.
  31243. */
  31244. get: function () {
  31245. return this._LODLevels.length > 0;
  31246. },
  31247. enumerable: true,
  31248. configurable: true
  31249. });
  31250. /**
  31251. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31252. * @returns an array of {BABYLON.MeshLODLevel}
  31253. */
  31254. Mesh.prototype.getLODLevels = function () {
  31255. return this._LODLevels;
  31256. };
  31257. Mesh.prototype._sortLODLevels = function () {
  31258. this._LODLevels.sort(function (a, b) {
  31259. if (a.distance < b.distance) {
  31260. return 1;
  31261. }
  31262. if (a.distance > b.distance) {
  31263. return -1;
  31264. }
  31265. return 0;
  31266. });
  31267. };
  31268. /**
  31269. * Add a mesh as LOD level triggered at the given distance.
  31270. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31271. * @param {number} distance The distance from the center of the object to show this level
  31272. * @param {Mesh} mesh The mesh to be added as LOD level
  31273. * @return {Mesh} This mesh (for chaining)
  31274. */
  31275. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31276. if (mesh && mesh._masterMesh) {
  31277. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31278. return this;
  31279. }
  31280. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31281. this._LODLevels.push(level);
  31282. if (mesh) {
  31283. mesh._masterMesh = this;
  31284. }
  31285. this._sortLODLevels();
  31286. return this;
  31287. };
  31288. /**
  31289. * Returns the LOD level mesh at the passed distance or null if not found.
  31290. * It is related to the method `addLODLevel(distance, mesh)`.
  31291. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31292. * Returns an object Mesh or `null`.
  31293. */
  31294. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31295. for (var index = 0; index < this._LODLevels.length; index++) {
  31296. var level = this._LODLevels[index];
  31297. if (level.distance === distance) {
  31298. return level.mesh;
  31299. }
  31300. }
  31301. return null;
  31302. };
  31303. /**
  31304. * Remove a mesh from the LOD array
  31305. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31306. * @param {Mesh} mesh The mesh to be removed.
  31307. * @return {Mesh} This mesh (for chaining)
  31308. */
  31309. Mesh.prototype.removeLODLevel = function (mesh) {
  31310. for (var index = 0; index < this._LODLevels.length; index++) {
  31311. if (this._LODLevels[index].mesh === mesh) {
  31312. this._LODLevels.splice(index, 1);
  31313. if (mesh) {
  31314. mesh._masterMesh = null;
  31315. }
  31316. }
  31317. }
  31318. this._sortLODLevels();
  31319. return this;
  31320. };
  31321. /**
  31322. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31323. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31324. */
  31325. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31326. if (!this._LODLevels || this._LODLevels.length === 0) {
  31327. return this;
  31328. }
  31329. var bSphere;
  31330. if (boundingSphere) {
  31331. bSphere = boundingSphere;
  31332. }
  31333. else {
  31334. var boundingInfo = this.getBoundingInfo();
  31335. bSphere = boundingInfo.boundingSphere;
  31336. }
  31337. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31338. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31339. if (this.onLODLevelSelection) {
  31340. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31341. }
  31342. return this;
  31343. }
  31344. for (var index = 0; index < this._LODLevels.length; index++) {
  31345. var level = this._LODLevels[index];
  31346. if (level.distance < distanceToCamera) {
  31347. if (level.mesh) {
  31348. level.mesh._preActivate();
  31349. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31350. }
  31351. if (this.onLODLevelSelection) {
  31352. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31353. }
  31354. return level.mesh;
  31355. }
  31356. }
  31357. if (this.onLODLevelSelection) {
  31358. this.onLODLevelSelection(distanceToCamera, this, this);
  31359. }
  31360. return this;
  31361. };
  31362. Object.defineProperty(Mesh.prototype, "geometry", {
  31363. /**
  31364. * Returns the mesh internal Geometry object.
  31365. */
  31366. get: function () {
  31367. return this._geometry;
  31368. },
  31369. enumerable: true,
  31370. configurable: true
  31371. });
  31372. /**
  31373. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31374. */
  31375. Mesh.prototype.getTotalVertices = function () {
  31376. if (this._geometry === null || this._geometry === undefined) {
  31377. return 0;
  31378. }
  31379. return this._geometry.getTotalVertices();
  31380. };
  31381. /**
  31382. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31383. * 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.
  31384. * You can force the copy with forceCopy === true
  31385. * Returns null if the mesh has no geometry or no vertex buffer.
  31386. * Possible `kind` values :
  31387. * - BABYLON.VertexBuffer.PositionKind
  31388. * - BABYLON.VertexBuffer.UVKind
  31389. * - BABYLON.VertexBuffer.UV2Kind
  31390. * - BABYLON.VertexBuffer.UV3Kind
  31391. * - BABYLON.VertexBuffer.UV4Kind
  31392. * - BABYLON.VertexBuffer.UV5Kind
  31393. * - BABYLON.VertexBuffer.UV6Kind
  31394. * - BABYLON.VertexBuffer.ColorKind
  31395. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31396. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31397. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31398. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31399. */
  31400. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31401. if (!this._geometry) {
  31402. return null;
  31403. }
  31404. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31405. };
  31406. /**
  31407. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31408. * Returns `null` if the mesh has no geometry.
  31409. * Possible `kind` values :
  31410. * - BABYLON.VertexBuffer.PositionKind
  31411. * - BABYLON.VertexBuffer.UVKind
  31412. * - BABYLON.VertexBuffer.UV2Kind
  31413. * - BABYLON.VertexBuffer.UV3Kind
  31414. * - BABYLON.VertexBuffer.UV4Kind
  31415. * - BABYLON.VertexBuffer.UV5Kind
  31416. * - BABYLON.VertexBuffer.UV6Kind
  31417. * - BABYLON.VertexBuffer.ColorKind
  31418. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31419. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31420. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31421. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31422. */
  31423. Mesh.prototype.getVertexBuffer = function (kind) {
  31424. if (!this._geometry) {
  31425. return null;
  31426. }
  31427. return this._geometry.getVertexBuffer(kind);
  31428. };
  31429. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31430. if (!this._geometry) {
  31431. if (this._delayInfo) {
  31432. return this._delayInfo.indexOf(kind) !== -1;
  31433. }
  31434. return false;
  31435. }
  31436. return this._geometry.isVerticesDataPresent(kind);
  31437. };
  31438. /**
  31439. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31440. * Possible `kind` values :
  31441. * - BABYLON.VertexBuffer.PositionKind
  31442. * - BABYLON.VertexBuffer.UVKind
  31443. * - BABYLON.VertexBuffer.UV2Kind
  31444. * - BABYLON.VertexBuffer.UV3Kind
  31445. * - BABYLON.VertexBuffer.UV4Kind
  31446. * - BABYLON.VertexBuffer.UV5Kind
  31447. * - BABYLON.VertexBuffer.UV6Kind
  31448. * - BABYLON.VertexBuffer.ColorKind
  31449. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31450. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31451. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31452. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31453. */
  31454. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31455. if (!this._geometry) {
  31456. if (this._delayInfo) {
  31457. return this._delayInfo.indexOf(kind) !== -1;
  31458. }
  31459. return false;
  31460. }
  31461. return this._geometry.isVertexBufferUpdatable(kind);
  31462. };
  31463. /**
  31464. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31465. * Possible `kind` values :
  31466. * - BABYLON.VertexBuffer.PositionKind
  31467. * - BABYLON.VertexBuffer.UVKind
  31468. * - BABYLON.VertexBuffer.UV2Kind
  31469. * - BABYLON.VertexBuffer.UV3Kind
  31470. * - BABYLON.VertexBuffer.UV4Kind
  31471. * - BABYLON.VertexBuffer.UV5Kind
  31472. * - BABYLON.VertexBuffer.UV6Kind
  31473. * - BABYLON.VertexBuffer.ColorKind
  31474. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31475. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31476. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31477. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31478. */
  31479. Mesh.prototype.getVerticesDataKinds = function () {
  31480. if (!this._geometry) {
  31481. var result = new Array();
  31482. if (this._delayInfo) {
  31483. this._delayInfo.forEach(function (kind, index, array) {
  31484. result.push(kind);
  31485. });
  31486. }
  31487. return result;
  31488. }
  31489. return this._geometry.getVerticesDataKinds();
  31490. };
  31491. /**
  31492. * Returns a positive integer : the total number of indices in this mesh geometry.
  31493. * Returns zero if the mesh has no geometry.
  31494. */
  31495. Mesh.prototype.getTotalIndices = function () {
  31496. if (!this._geometry) {
  31497. return 0;
  31498. }
  31499. return this._geometry.getTotalIndices();
  31500. };
  31501. /**
  31502. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31503. * 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.
  31504. * Returns an empty array if the mesh has no geometry.
  31505. */
  31506. Mesh.prototype.getIndices = function (copyWhenShared) {
  31507. if (!this._geometry) {
  31508. return [];
  31509. }
  31510. return this._geometry.getIndices(copyWhenShared);
  31511. };
  31512. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31513. get: function () {
  31514. return this._masterMesh !== null && this._masterMesh !== undefined;
  31515. },
  31516. enumerable: true,
  31517. configurable: true
  31518. });
  31519. /**
  31520. * Determine if the current mesh is ready to be rendered
  31521. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31522. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31523. * @returns true if all associated assets are ready (material, textures, shaders)
  31524. */
  31525. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31526. if (completeCheck === void 0) { completeCheck = false; }
  31527. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31528. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31529. return false;
  31530. }
  31531. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31532. return false;
  31533. }
  31534. if (!this.subMeshes || this.subMeshes.length === 0) {
  31535. return true;
  31536. }
  31537. if (!completeCheck) {
  31538. return true;
  31539. }
  31540. var engine = this.getEngine();
  31541. var scene = this.getScene();
  31542. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31543. this.computeWorldMatrix();
  31544. var mat = this.material || scene.defaultMaterial;
  31545. if (mat) {
  31546. if (mat.storeEffectOnSubMeshes) {
  31547. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31548. var subMesh = _a[_i];
  31549. var effectiveMaterial = subMesh.getMaterial();
  31550. if (effectiveMaterial) {
  31551. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31552. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31553. return false;
  31554. }
  31555. }
  31556. else {
  31557. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31558. return false;
  31559. }
  31560. }
  31561. }
  31562. }
  31563. }
  31564. else {
  31565. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31566. return false;
  31567. }
  31568. }
  31569. }
  31570. // Shadows
  31571. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31572. var light = _c[_b];
  31573. var generator = light.getShadowGenerator();
  31574. if (generator) {
  31575. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31576. var subMesh = _e[_d];
  31577. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31578. return false;
  31579. }
  31580. }
  31581. }
  31582. }
  31583. // LOD
  31584. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31585. var lod = _g[_f];
  31586. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31587. return false;
  31588. }
  31589. }
  31590. return true;
  31591. };
  31592. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31593. /**
  31594. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31595. * This property is pertinent only for updatable parametric shapes.
  31596. */
  31597. get: function () {
  31598. return this._areNormalsFrozen;
  31599. },
  31600. enumerable: true,
  31601. configurable: true
  31602. });
  31603. /**
  31604. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31605. * It has no effect at all on other shapes.
  31606. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31607. * Returns the Mesh.
  31608. */
  31609. Mesh.prototype.freezeNormals = function () {
  31610. this._areNormalsFrozen = true;
  31611. return this;
  31612. };
  31613. /**
  31614. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31615. * It has no effect at all on other shapes.
  31616. * It reactivates the mesh normals computation if it was previously frozen.
  31617. * Returns the Mesh.
  31618. */
  31619. Mesh.prototype.unfreezeNormals = function () {
  31620. this._areNormalsFrozen = false;
  31621. return this;
  31622. };
  31623. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31624. /**
  31625. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31626. */
  31627. set: function (count) {
  31628. this._overridenInstanceCount = count;
  31629. },
  31630. enumerable: true,
  31631. configurable: true
  31632. });
  31633. // Methods
  31634. Mesh.prototype._preActivate = function () {
  31635. var sceneRenderId = this.getScene().getRenderId();
  31636. if (this._preActivateId === sceneRenderId) {
  31637. return this;
  31638. }
  31639. this._preActivateId = sceneRenderId;
  31640. this._visibleInstances = null;
  31641. return this;
  31642. };
  31643. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31644. if (this._visibleInstances) {
  31645. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31646. }
  31647. return this;
  31648. };
  31649. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31650. if (!this._visibleInstances) {
  31651. this._visibleInstances = {};
  31652. this._visibleInstances.defaultRenderId = renderId;
  31653. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31654. }
  31655. if (!this._visibleInstances[renderId]) {
  31656. this._visibleInstances[renderId] = new Array();
  31657. }
  31658. this._visibleInstances[renderId].push(instance);
  31659. return this;
  31660. };
  31661. /**
  31662. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31663. * This means the mesh underlying bounding box and sphere are recomputed.
  31664. * Returns the Mesh.
  31665. */
  31666. Mesh.prototype.refreshBoundingInfo = function () {
  31667. return this._refreshBoundingInfo(false);
  31668. };
  31669. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31670. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31671. return this;
  31672. }
  31673. var data = this._getPositionData(applySkeleton);
  31674. if (data) {
  31675. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31676. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31677. }
  31678. if (this.subMeshes) {
  31679. for (var index = 0; index < this.subMeshes.length; index++) {
  31680. this.subMeshes[index].refreshBoundingInfo();
  31681. }
  31682. }
  31683. this._updateBoundingInfo();
  31684. return this;
  31685. };
  31686. Mesh.prototype._getPositionData = function (applySkeleton) {
  31687. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31688. if (data && applySkeleton && this.skeleton) {
  31689. data = BABYLON.Tools.Slice(data);
  31690. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31691. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31692. if (matricesWeightsData && matricesIndicesData) {
  31693. var needExtras = this.numBoneInfluencers > 4;
  31694. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31695. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31696. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31697. var tempVector = BABYLON.Tmp.Vector3[0];
  31698. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31699. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31700. var matWeightIdx = 0;
  31701. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31702. finalMatrix.reset();
  31703. var inf;
  31704. var weight;
  31705. for (inf = 0; inf < 4; inf++) {
  31706. weight = matricesWeightsData[matWeightIdx + inf];
  31707. if (weight <= 0)
  31708. break;
  31709. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31710. finalMatrix.addToSelf(tempMatrix);
  31711. }
  31712. if (needExtras) {
  31713. for (inf = 0; inf < 4; inf++) {
  31714. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31715. if (weight <= 0)
  31716. break;
  31717. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31718. finalMatrix.addToSelf(tempMatrix);
  31719. }
  31720. }
  31721. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31722. tempVector.toArray(data, index);
  31723. }
  31724. }
  31725. }
  31726. return data;
  31727. };
  31728. Mesh.prototype._createGlobalSubMesh = function (force) {
  31729. var totalVertices = this.getTotalVertices();
  31730. if (!totalVertices || !this.getIndices()) {
  31731. return null;
  31732. }
  31733. // Check if we need to recreate the submeshes
  31734. if (this.subMeshes && this.subMeshes.length > 0) {
  31735. var ib = this.getIndices();
  31736. if (!ib) {
  31737. return null;
  31738. }
  31739. var totalIndices = ib.length;
  31740. var needToRecreate = false;
  31741. if (force) {
  31742. needToRecreate = true;
  31743. }
  31744. else {
  31745. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31746. var submesh = _a[_i];
  31747. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31748. needToRecreate = true;
  31749. break;
  31750. }
  31751. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31752. needToRecreate = true;
  31753. break;
  31754. }
  31755. }
  31756. }
  31757. if (!needToRecreate) {
  31758. return this.subMeshes[0];
  31759. }
  31760. }
  31761. this.releaseSubMeshes();
  31762. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31763. };
  31764. Mesh.prototype.subdivide = function (count) {
  31765. if (count < 1) {
  31766. return;
  31767. }
  31768. var totalIndices = this.getTotalIndices();
  31769. var subdivisionSize = (totalIndices / count) | 0;
  31770. var offset = 0;
  31771. // Ensure that subdivisionSize is a multiple of 3
  31772. while (subdivisionSize % 3 !== 0) {
  31773. subdivisionSize++;
  31774. }
  31775. this.releaseSubMeshes();
  31776. for (var index = 0; index < count; index++) {
  31777. if (offset >= totalIndices) {
  31778. break;
  31779. }
  31780. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31781. offset += subdivisionSize;
  31782. }
  31783. this.synchronizeInstances();
  31784. };
  31785. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31786. if (updatable === void 0) { updatable = false; }
  31787. if (!this._geometry) {
  31788. var vertexData = new BABYLON.VertexData();
  31789. vertexData.set(data, kind);
  31790. var scene = this.getScene();
  31791. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31792. }
  31793. else {
  31794. this._geometry.setVerticesData(kind, data, updatable, stride);
  31795. }
  31796. return this;
  31797. };
  31798. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31799. if (updatable === void 0) { updatable = true; }
  31800. var vb = this.getVertexBuffer(kind);
  31801. if (!vb || vb.isUpdatable() === updatable) {
  31802. return;
  31803. }
  31804. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31805. };
  31806. /**
  31807. * Sets the mesh VertexBuffer.
  31808. * Returns the Mesh.
  31809. */
  31810. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31811. if (!this._geometry) {
  31812. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31813. }
  31814. this._geometry.setVerticesBuffer(buffer);
  31815. return this;
  31816. };
  31817. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31818. if (!this._geometry) {
  31819. return this;
  31820. }
  31821. if (!makeItUnique) {
  31822. this._geometry.updateVerticesData(kind, data, updateExtends);
  31823. }
  31824. else {
  31825. this.makeGeometryUnique();
  31826. this.updateVerticesData(kind, data, updateExtends, false);
  31827. }
  31828. return this;
  31829. };
  31830. /**
  31831. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31832. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31833. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31834. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31835. * Returns the Mesh.
  31836. */
  31837. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31838. if (computeNormals === void 0) { computeNormals = true; }
  31839. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31840. if (!positions) {
  31841. return this;
  31842. }
  31843. positionFunction(positions);
  31844. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31845. if (computeNormals) {
  31846. var indices = this.getIndices();
  31847. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31848. if (!normals) {
  31849. return this;
  31850. }
  31851. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31852. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31853. }
  31854. return this;
  31855. };
  31856. /**
  31857. * Creates a un-shared specific occurence of the geometry for the mesh.
  31858. * Returns the Mesh.
  31859. */
  31860. Mesh.prototype.makeGeometryUnique = function () {
  31861. if (!this._geometry) {
  31862. return this;
  31863. }
  31864. var oldGeometry = this._geometry;
  31865. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31866. oldGeometry.releaseForMesh(this, true);
  31867. geometry.applyToMesh(this);
  31868. return this;
  31869. };
  31870. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31871. if (totalVertices === void 0) { totalVertices = null; }
  31872. if (updatable === void 0) { updatable = false; }
  31873. if (!this._geometry) {
  31874. var vertexData = new BABYLON.VertexData();
  31875. vertexData.indices = indices;
  31876. var scene = this.getScene();
  31877. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31878. }
  31879. else {
  31880. this._geometry.setIndices(indices, totalVertices, updatable);
  31881. }
  31882. return this;
  31883. };
  31884. /**
  31885. * Update the current index buffer
  31886. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31887. * Returns the Mesh.
  31888. */
  31889. Mesh.prototype.updateIndices = function (indices, offset) {
  31890. if (!this._geometry) {
  31891. return this;
  31892. }
  31893. this._geometry.updateIndices(indices, offset);
  31894. return this;
  31895. };
  31896. /**
  31897. * Invert the geometry to move from a right handed system to a left handed one.
  31898. * Returns the Mesh.
  31899. */
  31900. Mesh.prototype.toLeftHanded = function () {
  31901. if (!this._geometry) {
  31902. return this;
  31903. }
  31904. this._geometry.toLeftHanded();
  31905. return this;
  31906. };
  31907. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31908. if (!this._geometry) {
  31909. return this;
  31910. }
  31911. var engine = this.getScene().getEngine();
  31912. // Wireframe
  31913. var indexToBind;
  31914. if (this._unIndexed) {
  31915. indexToBind = null;
  31916. }
  31917. else {
  31918. switch (fillMode) {
  31919. case BABYLON.Material.PointFillMode:
  31920. indexToBind = null;
  31921. break;
  31922. case BABYLON.Material.WireFrameFillMode:
  31923. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31924. break;
  31925. default:
  31926. case BABYLON.Material.TriangleFillMode:
  31927. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31928. break;
  31929. }
  31930. }
  31931. // VBOs
  31932. this._geometry._bind(effect, indexToBind);
  31933. return this;
  31934. };
  31935. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31936. if (alternate === void 0) { alternate = false; }
  31937. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31938. return this;
  31939. }
  31940. this.onBeforeDrawObservable.notifyObservers(this);
  31941. var scene = this.getScene();
  31942. var engine = scene.getEngine();
  31943. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31944. // or triangles as points
  31945. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31946. }
  31947. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31948. // Triangles as wireframe
  31949. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31950. }
  31951. else {
  31952. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31953. }
  31954. if (scene._isAlternateRenderingEnabled && !alternate) {
  31955. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31956. if (!effect || !scene.activeCamera) {
  31957. return this;
  31958. }
  31959. scene._switchToAlternateCameraConfiguration(true);
  31960. this._effectiveMaterial.bindView(effect);
  31961. this._effectiveMaterial.bindViewProjection(effect);
  31962. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31963. this._draw(subMesh, fillMode, instancesCount, true);
  31964. engine.setViewport(scene.activeCamera.viewport);
  31965. scene._switchToAlternateCameraConfiguration(false);
  31966. this._effectiveMaterial.bindView(effect);
  31967. this._effectiveMaterial.bindViewProjection(effect);
  31968. }
  31969. return this;
  31970. };
  31971. /**
  31972. * Registers for this mesh a javascript function called just before the rendering process.
  31973. * This function is passed the current mesh.
  31974. * Return the Mesh.
  31975. */
  31976. Mesh.prototype.registerBeforeRender = function (func) {
  31977. this.onBeforeRenderObservable.add(func);
  31978. return this;
  31979. };
  31980. /**
  31981. * Disposes a previously registered javascript function called before the rendering.
  31982. * This function is passed the current mesh.
  31983. * Returns the Mesh.
  31984. */
  31985. Mesh.prototype.unregisterBeforeRender = function (func) {
  31986. this.onBeforeRenderObservable.removeCallback(func);
  31987. return this;
  31988. };
  31989. /**
  31990. * Registers for this mesh a javascript function called just after the rendering is complete.
  31991. * This function is passed the current mesh.
  31992. * Returns the Mesh.
  31993. */
  31994. Mesh.prototype.registerAfterRender = function (func) {
  31995. this.onAfterRenderObservable.add(func);
  31996. return this;
  31997. };
  31998. /**
  31999. * Disposes a previously registered javascript function called after the rendering.
  32000. * This function is passed the current mesh.
  32001. * Return the Mesh.
  32002. */
  32003. Mesh.prototype.unregisterAfterRender = function (func) {
  32004. this.onAfterRenderObservable.removeCallback(func);
  32005. return this;
  32006. };
  32007. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32008. var scene = this.getScene();
  32009. this._batchCache.mustReturn = false;
  32010. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32011. this._batchCache.visibleInstances[subMeshId] = null;
  32012. if (this._visibleInstances) {
  32013. var currentRenderId = scene.getRenderId();
  32014. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32015. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32016. var selfRenderId = this._renderId;
  32017. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32018. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32019. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32020. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32021. }
  32022. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32023. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32024. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32025. this._batchCache.mustReturn = true;
  32026. return this._batchCache;
  32027. }
  32028. if (currentRenderId !== selfRenderId) {
  32029. this._batchCache.renderSelf[subMeshId] = false;
  32030. }
  32031. }
  32032. this._renderIdForInstances[subMeshId] = currentRenderId;
  32033. }
  32034. return this._batchCache;
  32035. };
  32036. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32037. var visibleInstances = batch.visibleInstances[subMesh._id];
  32038. if (!visibleInstances) {
  32039. return this;
  32040. }
  32041. var matricesCount = visibleInstances.length + 1;
  32042. var bufferSize = matricesCount * 16 * 4;
  32043. var currentInstancesBufferSize = this._instancesBufferSize;
  32044. var instancesBuffer = this._instancesBuffer;
  32045. while (this._instancesBufferSize < bufferSize) {
  32046. this._instancesBufferSize *= 2;
  32047. }
  32048. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32049. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32050. }
  32051. var offset = 0;
  32052. var instancesCount = 0;
  32053. var world = this.getWorldMatrix();
  32054. if (batch.renderSelf[subMesh._id]) {
  32055. world.copyToArray(this._instancesData, offset);
  32056. offset += 16;
  32057. instancesCount++;
  32058. }
  32059. if (visibleInstances) {
  32060. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32061. var instance = visibleInstances[instanceIndex];
  32062. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32063. offset += 16;
  32064. instancesCount++;
  32065. }
  32066. }
  32067. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32068. if (instancesBuffer) {
  32069. instancesBuffer.dispose();
  32070. }
  32071. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32072. this._instancesBuffer = instancesBuffer;
  32073. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32074. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32075. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32076. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32077. }
  32078. else {
  32079. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32080. }
  32081. this._bind(subMesh, effect, fillMode);
  32082. this._draw(subMesh, fillMode, instancesCount);
  32083. engine.unbindInstanceAttributes();
  32084. return this;
  32085. };
  32086. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32087. var scene = this.getScene();
  32088. var engine = scene.getEngine();
  32089. if (hardwareInstancedRendering) {
  32090. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32091. }
  32092. else {
  32093. if (batch.renderSelf[subMesh._id]) {
  32094. // Draw
  32095. if (onBeforeDraw) {
  32096. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32097. }
  32098. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32099. }
  32100. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32101. if (visibleInstancesForSubMesh) {
  32102. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32103. var instance = visibleInstancesForSubMesh[instanceIndex];
  32104. // World
  32105. var world = instance.getWorldMatrix();
  32106. if (onBeforeDraw) {
  32107. onBeforeDraw(true, world, effectiveMaterial);
  32108. }
  32109. // Draw
  32110. this._draw(subMesh, fillMode);
  32111. }
  32112. }
  32113. }
  32114. return this;
  32115. };
  32116. /**
  32117. * Triggers the draw call for the mesh.
  32118. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32119. * Returns the Mesh.
  32120. */
  32121. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32122. this._checkOcclusionQuery();
  32123. if (this._isOccluded) {
  32124. return this;
  32125. }
  32126. var scene = this.getScene();
  32127. // Managing instances
  32128. var batch = this._getInstancesRenderList(subMesh._id);
  32129. if (batch.mustReturn) {
  32130. return this;
  32131. }
  32132. // Checking geometry state
  32133. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32134. return this;
  32135. }
  32136. this.onBeforeRenderObservable.notifyObservers(this);
  32137. var engine = scene.getEngine();
  32138. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32139. // Material
  32140. var material = subMesh.getMaterial();
  32141. if (!material) {
  32142. return this;
  32143. }
  32144. this._effectiveMaterial = material;
  32145. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32146. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32147. return this;
  32148. }
  32149. }
  32150. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32151. return this;
  32152. }
  32153. // Alpha mode
  32154. if (enableAlphaMode) {
  32155. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32156. }
  32157. // Outline - step 1
  32158. var savedDepthWrite = engine.getDepthWrite();
  32159. if (this.renderOutline) {
  32160. engine.setDepthWrite(false);
  32161. scene.getOutlineRenderer().render(subMesh, batch);
  32162. engine.setDepthWrite(savedDepthWrite);
  32163. }
  32164. var effect;
  32165. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32166. effect = subMesh.effect;
  32167. }
  32168. else {
  32169. effect = this._effectiveMaterial.getEffect();
  32170. }
  32171. if (!effect) {
  32172. return this;
  32173. }
  32174. var sideOrientation = this.overrideMaterialSideOrientation;
  32175. if (sideOrientation == null) {
  32176. sideOrientation = this._effectiveMaterial.sideOrientation;
  32177. if (this._getWorldMatrixDeterminant() < 0) {
  32178. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32179. }
  32180. }
  32181. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32182. if (this._effectiveMaterial.forceDepthWrite) {
  32183. engine.setDepthWrite(true);
  32184. }
  32185. // Bind
  32186. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32187. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32188. this._bind(subMesh, effect, fillMode);
  32189. }
  32190. var world = this.getWorldMatrix();
  32191. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32192. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32193. }
  32194. else {
  32195. this._effectiveMaterial.bind(world, this);
  32196. }
  32197. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32198. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32199. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32200. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32201. }
  32202. // Draw
  32203. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32204. // Unbind
  32205. this._effectiveMaterial.unbind();
  32206. // Outline - step 2
  32207. if (this.renderOutline && savedDepthWrite) {
  32208. engine.setDepthWrite(true);
  32209. engine.setColorWrite(false);
  32210. scene.getOutlineRenderer().render(subMesh, batch);
  32211. engine.setColorWrite(true);
  32212. }
  32213. // Overlay
  32214. if (this.renderOverlay) {
  32215. var currentMode = engine.getAlphaMode();
  32216. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32217. scene.getOutlineRenderer().render(subMesh, batch, true);
  32218. engine.setAlphaMode(currentMode);
  32219. }
  32220. this.onAfterRenderObservable.notifyObservers(this);
  32221. return this;
  32222. };
  32223. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32224. if (isInstance && effectiveMaterial) {
  32225. effectiveMaterial.bindOnlyWorldMatrix(world);
  32226. }
  32227. };
  32228. /**
  32229. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32230. */
  32231. Mesh.prototype.getEmittedParticleSystems = function () {
  32232. var results = new Array();
  32233. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32234. var particleSystem = this.getScene().particleSystems[index];
  32235. if (particleSystem.emitter === this) {
  32236. results.push(particleSystem);
  32237. }
  32238. }
  32239. return results;
  32240. };
  32241. /**
  32242. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32243. */
  32244. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32245. var results = new Array();
  32246. var descendants = this.getDescendants();
  32247. descendants.push(this);
  32248. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32249. var particleSystem = this.getScene().particleSystems[index];
  32250. var emitter = particleSystem.emitter;
  32251. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32252. results.push(particleSystem);
  32253. }
  32254. }
  32255. return results;
  32256. };
  32257. /**
  32258. * Normalize matrix weights so that all vertices have a total weight set to 1
  32259. */
  32260. Mesh.prototype.cleanMatrixWeights = function () {
  32261. var epsilon = 1e-3;
  32262. var noInfluenceBoneIndex = 0.0;
  32263. if (this.skeleton) {
  32264. noInfluenceBoneIndex = this.skeleton.bones.length;
  32265. }
  32266. else {
  32267. return;
  32268. }
  32269. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32270. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32271. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32272. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32273. var influencers = this.numBoneInfluencers;
  32274. var size = matricesWeights.length;
  32275. for (var i = 0; i < size; i += 4) {
  32276. var weight = 0.0;
  32277. var firstZeroWeight = -1;
  32278. for (var j = 0; j < 4; j++) {
  32279. var w = matricesWeights[i + j];
  32280. weight += w;
  32281. if (w < epsilon && firstZeroWeight < 0) {
  32282. firstZeroWeight = j;
  32283. }
  32284. }
  32285. if (matricesWeightsExtra) {
  32286. for (var j = 0; j < 4; j++) {
  32287. var w = matricesWeightsExtra[i + j];
  32288. weight += w;
  32289. if (w < epsilon && firstZeroWeight < 0) {
  32290. firstZeroWeight = j + 4;
  32291. }
  32292. }
  32293. }
  32294. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32295. firstZeroWeight = influencers - 1;
  32296. }
  32297. if (weight > epsilon) {
  32298. var mweight = 1.0 / weight;
  32299. for (var j = 0; j < 4; j++) {
  32300. matricesWeights[i + j] *= mweight;
  32301. }
  32302. if (matricesWeightsExtra) {
  32303. for (var j = 0; j < 4; j++) {
  32304. matricesWeightsExtra[i + j] *= mweight;
  32305. }
  32306. }
  32307. }
  32308. else {
  32309. if (firstZeroWeight >= 4) {
  32310. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32311. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32312. }
  32313. else {
  32314. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32315. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32316. }
  32317. }
  32318. }
  32319. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32320. if (matricesIndicesExtra) {
  32321. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32322. }
  32323. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32324. if (matricesWeightsExtra) {
  32325. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32326. }
  32327. };
  32328. Mesh.prototype._checkDelayState = function () {
  32329. var scene = this.getScene();
  32330. if (this._geometry) {
  32331. this._geometry.load(scene);
  32332. }
  32333. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32334. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32335. this._queueLoad(scene);
  32336. }
  32337. return this;
  32338. };
  32339. Mesh.prototype._queueLoad = function (scene) {
  32340. var _this = this;
  32341. scene._addPendingData(this);
  32342. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32343. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32344. if (data instanceof ArrayBuffer) {
  32345. _this._delayLoadingFunction(data, _this);
  32346. }
  32347. else {
  32348. _this._delayLoadingFunction(JSON.parse(data), _this);
  32349. }
  32350. _this.instances.forEach(function (instance) {
  32351. instance._syncSubMeshes();
  32352. });
  32353. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32354. scene._removePendingData(_this);
  32355. }, function () { }, scene.database, getBinaryData);
  32356. return this;
  32357. };
  32358. /**
  32359. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32360. */
  32361. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32362. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32363. return false;
  32364. }
  32365. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32366. return false;
  32367. }
  32368. this._checkDelayState();
  32369. return true;
  32370. };
  32371. /**
  32372. * Sets the mesh material by the material or multiMaterial `id` property.
  32373. * The material `id` is a string identifying the material or the multiMaterial.
  32374. * This method returns the Mesh.
  32375. */
  32376. Mesh.prototype.setMaterialByID = function (id) {
  32377. var materials = this.getScene().materials;
  32378. var index;
  32379. for (index = materials.length - 1; index > -1; index--) {
  32380. if (materials[index].id === id) {
  32381. this.material = materials[index];
  32382. return this;
  32383. }
  32384. }
  32385. // Multi
  32386. var multiMaterials = this.getScene().multiMaterials;
  32387. for (index = multiMaterials.length - 1; index > -1; index--) {
  32388. if (multiMaterials[index].id === id) {
  32389. this.material = multiMaterials[index];
  32390. return this;
  32391. }
  32392. }
  32393. return this;
  32394. };
  32395. /**
  32396. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32397. */
  32398. Mesh.prototype.getAnimatables = function () {
  32399. var results = new Array();
  32400. if (this.material) {
  32401. results.push(this.material);
  32402. }
  32403. if (this.skeleton) {
  32404. results.push(this.skeleton);
  32405. }
  32406. return results;
  32407. };
  32408. /**
  32409. * Modifies the mesh geometry according to the passed transformation matrix.
  32410. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32411. * The mesh normals are modified accordingly the same transformation.
  32412. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32413. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32414. * Returns the Mesh.
  32415. */
  32416. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32417. // Position
  32418. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32419. return this;
  32420. }
  32421. var submeshes = this.subMeshes.splice(0);
  32422. this._resetPointsArrayCache();
  32423. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32424. var temp = new Array();
  32425. var index;
  32426. for (index = 0; index < data.length; index += 3) {
  32427. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32428. }
  32429. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32430. // Normals
  32431. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32432. return this;
  32433. }
  32434. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32435. temp = [];
  32436. for (index = 0; index < data.length; index += 3) {
  32437. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32438. }
  32439. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32440. // flip faces?
  32441. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32442. this.flipFaces();
  32443. }
  32444. // Restore submeshes
  32445. this.releaseSubMeshes();
  32446. this.subMeshes = submeshes;
  32447. return this;
  32448. };
  32449. /**
  32450. * Modifies the mesh geometry according to its own current World Matrix.
  32451. * The mesh World Matrix is then reset.
  32452. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32453. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32454. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32455. * Returns the Mesh.
  32456. */
  32457. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32458. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32459. this.scaling.copyFromFloats(1, 1, 1);
  32460. this.position.copyFromFloats(0, 0, 0);
  32461. this.rotation.copyFromFloats(0, 0, 0);
  32462. //only if quaternion is already set
  32463. if (this.rotationQuaternion) {
  32464. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32465. }
  32466. this._worldMatrix = BABYLON.Matrix.Identity();
  32467. return this;
  32468. };
  32469. Object.defineProperty(Mesh.prototype, "_positions", {
  32470. // Cache
  32471. get: function () {
  32472. if (this._geometry) {
  32473. return this._geometry._positions;
  32474. }
  32475. return null;
  32476. },
  32477. enumerable: true,
  32478. configurable: true
  32479. });
  32480. Mesh.prototype._resetPointsArrayCache = function () {
  32481. if (this._geometry) {
  32482. this._geometry._resetPointsArrayCache();
  32483. }
  32484. return this;
  32485. };
  32486. Mesh.prototype._generatePointsArray = function () {
  32487. if (this._geometry) {
  32488. return this._geometry._generatePointsArray();
  32489. }
  32490. return false;
  32491. };
  32492. /**
  32493. * Returns a new Mesh object generated from the current mesh properties.
  32494. * This method must not get confused with createInstance().
  32495. * The parameter `name` is a string, the name given to the new mesh.
  32496. * The optional parameter `newParent` can be any Node object (default `null`).
  32497. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32498. * 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.
  32499. */
  32500. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32501. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32502. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32503. };
  32504. /**
  32505. * Releases resources associated with this mesh.
  32506. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32507. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32508. */
  32509. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32510. var _this = this;
  32511. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32512. this.morphTargetManager = null;
  32513. if (this._geometry) {
  32514. this._geometry.releaseForMesh(this, true);
  32515. }
  32516. // Sources
  32517. var meshes = this.getScene().meshes;
  32518. meshes.forEach(function (abstractMesh) {
  32519. var mesh = abstractMesh;
  32520. if (mesh._source && mesh._source === _this) {
  32521. mesh._source = null;
  32522. }
  32523. });
  32524. this._source = null;
  32525. // Instances
  32526. if (this._instancesBuffer) {
  32527. this._instancesBuffer.dispose();
  32528. this._instancesBuffer = null;
  32529. }
  32530. while (this.instances.length) {
  32531. this.instances[0].dispose();
  32532. }
  32533. // Effect layers.
  32534. var effectLayers = this.getScene().effectLayers;
  32535. for (var i = 0; i < effectLayers.length; i++) {
  32536. var effectLayer = effectLayers[i];
  32537. if (effectLayer) {
  32538. effectLayer._disposeMesh(this);
  32539. }
  32540. }
  32541. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32542. };
  32543. /**
  32544. * Modifies the mesh geometry according to a displacement map.
  32545. * 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.
  32546. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32547. * This method returns nothing.
  32548. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32549. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32550. * 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.
  32551. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32552. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32553. *
  32554. * Returns the Mesh.
  32555. */
  32556. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32557. var _this = this;
  32558. var scene = this.getScene();
  32559. var onload = function (img) {
  32560. // Getting height map data
  32561. var canvas = document.createElement("canvas");
  32562. var context = canvas.getContext("2d");
  32563. var heightMapWidth = img.width;
  32564. var heightMapHeight = img.height;
  32565. canvas.width = heightMapWidth;
  32566. canvas.height = heightMapHeight;
  32567. context.drawImage(img, 0, 0);
  32568. // Create VertexData from map data
  32569. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32570. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32571. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32572. //execute success callback, if set
  32573. if (onSuccess) {
  32574. onSuccess(_this);
  32575. }
  32576. };
  32577. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32578. return this;
  32579. };
  32580. /**
  32581. * Modifies the mesh geometry according to a displacementMap buffer.
  32582. * 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.
  32583. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32584. * This method returns nothing.
  32585. * 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.
  32586. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32587. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32588. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32589. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32590. *
  32591. * Returns the Mesh.
  32592. */
  32593. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32594. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32595. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32596. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32597. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32598. return this;
  32599. }
  32600. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32601. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32602. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32603. var position = BABYLON.Vector3.Zero();
  32604. var normal = BABYLON.Vector3.Zero();
  32605. var uv = BABYLON.Vector2.Zero();
  32606. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32607. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32608. for (var index = 0; index < positions.length; index += 3) {
  32609. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32610. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32611. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32612. // Compute height
  32613. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32614. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32615. var pos = (u + v * heightMapWidth) * 4;
  32616. var r = buffer[pos] / 255.0;
  32617. var g = buffer[pos + 1] / 255.0;
  32618. var b = buffer[pos + 2] / 255.0;
  32619. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32620. normal.normalize();
  32621. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32622. position = position.add(normal);
  32623. position.toArray(positions, index);
  32624. }
  32625. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32626. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32627. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32628. return this;
  32629. };
  32630. /**
  32631. * Modify the mesh to get a flat shading rendering.
  32632. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32633. * This method returns the Mesh.
  32634. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32635. */
  32636. Mesh.prototype.convertToFlatShadedMesh = function () {
  32637. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32638. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32639. var kinds = this.getVerticesDataKinds();
  32640. var vbs = {};
  32641. var data = {};
  32642. var newdata = {};
  32643. var updatableNormals = false;
  32644. var kindIndex;
  32645. var kind;
  32646. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32647. kind = kinds[kindIndex];
  32648. var vertexBuffer = this.getVertexBuffer(kind);
  32649. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32650. updatableNormals = vertexBuffer.isUpdatable();
  32651. kinds.splice(kindIndex, 1);
  32652. kindIndex--;
  32653. continue;
  32654. }
  32655. vbs[kind] = vertexBuffer;
  32656. data[kind] = vbs[kind].getData();
  32657. newdata[kind] = [];
  32658. }
  32659. // Save previous submeshes
  32660. var previousSubmeshes = this.subMeshes.slice(0);
  32661. var indices = this.getIndices();
  32662. var totalIndices = this.getTotalIndices();
  32663. // Generating unique vertices per face
  32664. var index;
  32665. for (index = 0; index < totalIndices; index++) {
  32666. var vertexIndex = indices[index];
  32667. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32668. kind = kinds[kindIndex];
  32669. var stride = vbs[kind].getStrideSize();
  32670. for (var offset = 0; offset < stride; offset++) {
  32671. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32672. }
  32673. }
  32674. }
  32675. // Updating faces & normal
  32676. var normals = [];
  32677. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32678. for (index = 0; index < totalIndices; index += 3) {
  32679. indices[index] = index;
  32680. indices[index + 1] = index + 1;
  32681. indices[index + 2] = index + 2;
  32682. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32683. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32684. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32685. var p1p2 = p1.subtract(p2);
  32686. var p3p2 = p3.subtract(p2);
  32687. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32688. // Store same normals for every vertex
  32689. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32690. normals.push(normal.x);
  32691. normals.push(normal.y);
  32692. normals.push(normal.z);
  32693. }
  32694. }
  32695. this.setIndices(indices);
  32696. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32697. // Updating vertex buffers
  32698. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32699. kind = kinds[kindIndex];
  32700. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32701. }
  32702. // Updating submeshes
  32703. this.releaseSubMeshes();
  32704. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32705. var previousOne = previousSubmeshes[submeshIndex];
  32706. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32707. }
  32708. this.synchronizeInstances();
  32709. return this;
  32710. };
  32711. /**
  32712. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32713. * In other words, more vertices, no more indices and a single bigger VBO.
  32714. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32715. * Returns the Mesh.
  32716. */
  32717. Mesh.prototype.convertToUnIndexedMesh = function () {
  32718. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32719. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32720. var kinds = this.getVerticesDataKinds();
  32721. var vbs = {};
  32722. var data = {};
  32723. var newdata = {};
  32724. var kindIndex;
  32725. var kind;
  32726. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32727. kind = kinds[kindIndex];
  32728. var vertexBuffer = this.getVertexBuffer(kind);
  32729. vbs[kind] = vertexBuffer;
  32730. data[kind] = vbs[kind].getData();
  32731. newdata[kind] = [];
  32732. }
  32733. // Save previous submeshes
  32734. var previousSubmeshes = this.subMeshes.slice(0);
  32735. var indices = this.getIndices();
  32736. var totalIndices = this.getTotalIndices();
  32737. // Generating unique vertices per face
  32738. var index;
  32739. for (index = 0; index < totalIndices; index++) {
  32740. var vertexIndex = indices[index];
  32741. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32742. kind = kinds[kindIndex];
  32743. var stride = vbs[kind].getStrideSize();
  32744. for (var offset = 0; offset < stride; offset++) {
  32745. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32746. }
  32747. }
  32748. }
  32749. // Updating indices
  32750. for (index = 0; index < totalIndices; index += 3) {
  32751. indices[index] = index;
  32752. indices[index + 1] = index + 1;
  32753. indices[index + 2] = index + 2;
  32754. }
  32755. this.setIndices(indices);
  32756. // Updating vertex buffers
  32757. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32758. kind = kinds[kindIndex];
  32759. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32760. }
  32761. // Updating submeshes
  32762. this.releaseSubMeshes();
  32763. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32764. var previousOne = previousSubmeshes[submeshIndex];
  32765. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32766. }
  32767. this._unIndexed = true;
  32768. this.synchronizeInstances();
  32769. return this;
  32770. };
  32771. /**
  32772. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32773. * This method returns the Mesh.
  32774. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32775. */
  32776. Mesh.prototype.flipFaces = function (flipNormals) {
  32777. if (flipNormals === void 0) { flipNormals = false; }
  32778. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32779. var i;
  32780. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32781. for (i = 0; i < vertex_data.normals.length; i++) {
  32782. vertex_data.normals[i] *= -1;
  32783. }
  32784. }
  32785. if (vertex_data.indices) {
  32786. var temp;
  32787. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32788. // reassign indices
  32789. temp = vertex_data.indices[i + 1];
  32790. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32791. vertex_data.indices[i + 2] = temp;
  32792. }
  32793. }
  32794. vertex_data.applyToMesh(this);
  32795. return this;
  32796. };
  32797. // Instances
  32798. /**
  32799. * Creates a new InstancedMesh object from the mesh model.
  32800. * An instance shares the same properties and the same material than its model.
  32801. * Only these properties of each instance can then be set individually :
  32802. * - position
  32803. * - rotation
  32804. * - rotationQuaternion
  32805. * - setPivotMatrix
  32806. * - scaling
  32807. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32808. * Warning : this method is not supported for Line mesh and LineSystem
  32809. */
  32810. Mesh.prototype.createInstance = function (name) {
  32811. return new BABYLON.InstancedMesh(name, this);
  32812. };
  32813. /**
  32814. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32815. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32816. * This method returns the Mesh.
  32817. */
  32818. Mesh.prototype.synchronizeInstances = function () {
  32819. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32820. var instance = this.instances[instanceIndex];
  32821. instance._syncSubMeshes();
  32822. }
  32823. return this;
  32824. };
  32825. /**
  32826. * Simplify the mesh according to the given array of settings.
  32827. * Function will return immediately and will simplify async. It returns the Mesh.
  32828. * @param settings a collection of simplification settings.
  32829. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32830. * @param type the type of simplification to run.
  32831. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32832. */
  32833. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32834. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32835. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32836. this.getScene().simplificationQueue.addTask({
  32837. settings: settings,
  32838. parallelProcessing: parallelProcessing,
  32839. mesh: this,
  32840. simplificationType: simplificationType,
  32841. successCallback: successCallback
  32842. });
  32843. return this;
  32844. };
  32845. /**
  32846. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32847. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32848. * This should be used together with the simplification to avoid disappearing triangles.
  32849. * Returns the Mesh.
  32850. * @param successCallback an optional success callback to be called after the optimization finished.
  32851. */
  32852. Mesh.prototype.optimizeIndices = function (successCallback) {
  32853. var _this = this;
  32854. var indices = this.getIndices();
  32855. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32856. if (!positions || !indices) {
  32857. return this;
  32858. }
  32859. var vectorPositions = new Array();
  32860. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32861. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32862. }
  32863. var dupes = new Array();
  32864. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32865. var realPos = vectorPositions.length - 1 - iteration;
  32866. var testedPosition = vectorPositions[realPos];
  32867. for (var j = 0; j < realPos; ++j) {
  32868. var againstPosition = vectorPositions[j];
  32869. if (testedPosition.equals(againstPosition)) {
  32870. dupes[realPos] = j;
  32871. break;
  32872. }
  32873. }
  32874. }, function () {
  32875. for (var i = 0; i < indices.length; ++i) {
  32876. indices[i] = dupes[indices[i]] || indices[i];
  32877. }
  32878. //indices are now reordered
  32879. var originalSubMeshes = _this.subMeshes.slice(0);
  32880. _this.setIndices(indices);
  32881. _this.subMeshes = originalSubMeshes;
  32882. if (successCallback) {
  32883. successCallback(_this);
  32884. }
  32885. });
  32886. return this;
  32887. };
  32888. Mesh.prototype.serialize = function (serializationObject) {
  32889. serializationObject.name = this.name;
  32890. serializationObject.id = this.id;
  32891. serializationObject.type = this.getClassName();
  32892. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32893. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32894. }
  32895. serializationObject.position = this.position.asArray();
  32896. if (this.rotationQuaternion) {
  32897. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32898. }
  32899. else if (this.rotation) {
  32900. serializationObject.rotation = this.rotation.asArray();
  32901. }
  32902. serializationObject.scaling = this.scaling.asArray();
  32903. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32904. serializationObject.isEnabled = this.isEnabled(false);
  32905. serializationObject.isVisible = this.isVisible;
  32906. serializationObject.infiniteDistance = this.infiniteDistance;
  32907. serializationObject.pickable = this.isPickable;
  32908. serializationObject.receiveShadows = this.receiveShadows;
  32909. serializationObject.billboardMode = this.billboardMode;
  32910. serializationObject.visibility = this.visibility;
  32911. serializationObject.checkCollisions = this.checkCollisions;
  32912. serializationObject.isBlocker = this.isBlocker;
  32913. // Parent
  32914. if (this.parent) {
  32915. serializationObject.parentId = this.parent.id;
  32916. }
  32917. // Geometry
  32918. serializationObject.isUnIndexed = this.isUnIndexed;
  32919. var geometry = this._geometry;
  32920. if (geometry) {
  32921. var geometryId = geometry.id;
  32922. serializationObject.geometryId = geometryId;
  32923. // SubMeshes
  32924. serializationObject.subMeshes = [];
  32925. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32926. var subMesh = this.subMeshes[subIndex];
  32927. serializationObject.subMeshes.push({
  32928. materialIndex: subMesh.materialIndex,
  32929. verticesStart: subMesh.verticesStart,
  32930. verticesCount: subMesh.verticesCount,
  32931. indexStart: subMesh.indexStart,
  32932. indexCount: subMesh.indexCount
  32933. });
  32934. }
  32935. }
  32936. // Material
  32937. if (this.material) {
  32938. serializationObject.materialId = this.material.id;
  32939. }
  32940. else {
  32941. this.material = null;
  32942. }
  32943. // Morph targets
  32944. if (this.morphTargetManager) {
  32945. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32946. }
  32947. // Skeleton
  32948. if (this.skeleton) {
  32949. serializationObject.skeletonId = this.skeleton.id;
  32950. }
  32951. // Physics
  32952. //TODO implement correct serialization for physics impostors.
  32953. var impostor = this.getPhysicsImpostor();
  32954. if (impostor) {
  32955. serializationObject.physicsMass = impostor.getParam("mass");
  32956. serializationObject.physicsFriction = impostor.getParam("friction");
  32957. serializationObject.physicsRestitution = impostor.getParam("mass");
  32958. serializationObject.physicsImpostor = impostor.type;
  32959. }
  32960. // Metadata
  32961. if (this.metadata) {
  32962. serializationObject.metadata = this.metadata;
  32963. }
  32964. // Instances
  32965. serializationObject.instances = [];
  32966. for (var index = 0; index < this.instances.length; index++) {
  32967. var instance = this.instances[index];
  32968. var serializationInstance = {
  32969. name: instance.name,
  32970. id: instance.id,
  32971. position: instance.position.asArray(),
  32972. scaling: instance.scaling.asArray()
  32973. };
  32974. if (instance.rotationQuaternion) {
  32975. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32976. }
  32977. else if (instance.rotation) {
  32978. serializationInstance.rotation = instance.rotation.asArray();
  32979. }
  32980. serializationObject.instances.push(serializationInstance);
  32981. // Animations
  32982. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32983. serializationInstance.ranges = instance.serializeAnimationRanges();
  32984. }
  32985. //
  32986. // Animations
  32987. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32988. serializationObject.ranges = this.serializeAnimationRanges();
  32989. // Layer mask
  32990. serializationObject.layerMask = this.layerMask;
  32991. // Alpha
  32992. serializationObject.alphaIndex = this.alphaIndex;
  32993. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32994. // Overlay
  32995. serializationObject.overlayAlpha = this.overlayAlpha;
  32996. serializationObject.overlayColor = this.overlayColor.asArray();
  32997. serializationObject.renderOverlay = this.renderOverlay;
  32998. // Fog
  32999. serializationObject.applyFog = this.applyFog;
  33000. // Action Manager
  33001. if (this.actionManager) {
  33002. serializationObject.actions = this.actionManager.serialize(this.name);
  33003. }
  33004. };
  33005. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33006. if (!this.geometry) {
  33007. return;
  33008. }
  33009. this._markSubMeshesAsAttributesDirty();
  33010. var morphTargetManager = this._morphTargetManager;
  33011. if (morphTargetManager && morphTargetManager.vertexCount) {
  33012. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33013. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33014. this.morphTargetManager = null;
  33015. return;
  33016. }
  33017. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33018. var morphTarget = morphTargetManager.getActiveTarget(index);
  33019. var positions = morphTarget.getPositions();
  33020. if (!positions) {
  33021. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33022. return;
  33023. }
  33024. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33025. var normals = morphTarget.getNormals();
  33026. if (normals) {
  33027. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33028. }
  33029. var tangents = morphTarget.getTangents();
  33030. if (tangents) {
  33031. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33032. }
  33033. }
  33034. }
  33035. else {
  33036. var index = 0;
  33037. // Positions
  33038. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33039. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33040. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33041. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33042. }
  33043. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33044. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33045. }
  33046. index++;
  33047. }
  33048. }
  33049. };
  33050. // Statics
  33051. /**
  33052. * Returns a new Mesh object parsed from the source provided.
  33053. * The parameter `parsedMesh` is the source.
  33054. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33055. */
  33056. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33057. var mesh;
  33058. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33059. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33060. }
  33061. else {
  33062. mesh = new Mesh(parsedMesh.name, scene);
  33063. }
  33064. mesh.id = parsedMesh.id;
  33065. if (BABYLON.Tags) {
  33066. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33067. }
  33068. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33069. if (parsedMesh.metadata !== undefined) {
  33070. mesh.metadata = parsedMesh.metadata;
  33071. }
  33072. if (parsedMesh.rotationQuaternion) {
  33073. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33074. }
  33075. else if (parsedMesh.rotation) {
  33076. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33077. }
  33078. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33079. if (parsedMesh.localMatrix) {
  33080. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33081. }
  33082. else if (parsedMesh.pivotMatrix) {
  33083. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33084. }
  33085. mesh.setEnabled(parsedMesh.isEnabled);
  33086. mesh.isVisible = parsedMesh.isVisible;
  33087. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33088. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33089. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33090. if (parsedMesh.applyFog !== undefined) {
  33091. mesh.applyFog = parsedMesh.applyFog;
  33092. }
  33093. if (parsedMesh.pickable !== undefined) {
  33094. mesh.isPickable = parsedMesh.pickable;
  33095. }
  33096. if (parsedMesh.alphaIndex !== undefined) {
  33097. mesh.alphaIndex = parsedMesh.alphaIndex;
  33098. }
  33099. mesh.receiveShadows = parsedMesh.receiveShadows;
  33100. mesh.billboardMode = parsedMesh.billboardMode;
  33101. if (parsedMesh.visibility !== undefined) {
  33102. mesh.visibility = parsedMesh.visibility;
  33103. }
  33104. mesh.checkCollisions = parsedMesh.checkCollisions;
  33105. if (parsedMesh.isBlocker !== undefined) {
  33106. mesh.isBlocker = parsedMesh.isBlocker;
  33107. }
  33108. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33109. // freezeWorldMatrix
  33110. if (parsedMesh.freezeWorldMatrix) {
  33111. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33112. }
  33113. // Parent
  33114. if (parsedMesh.parentId) {
  33115. mesh._waitingParentId = parsedMesh.parentId;
  33116. }
  33117. // Actions
  33118. if (parsedMesh.actions !== undefined) {
  33119. mesh._waitingActions = parsedMesh.actions;
  33120. }
  33121. // Overlay
  33122. if (parsedMesh.overlayAlpha !== undefined) {
  33123. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33124. }
  33125. if (parsedMesh.overlayColor !== undefined) {
  33126. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33127. }
  33128. if (parsedMesh.renderOverlay !== undefined) {
  33129. mesh.renderOverlay = parsedMesh.renderOverlay;
  33130. }
  33131. // Geometry
  33132. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33133. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33134. if (parsedMesh.delayLoadingFile) {
  33135. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33136. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33137. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33138. if (parsedMesh._binaryInfo) {
  33139. mesh._binaryInfo = parsedMesh._binaryInfo;
  33140. }
  33141. mesh._delayInfo = [];
  33142. if (parsedMesh.hasUVs) {
  33143. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33144. }
  33145. if (parsedMesh.hasUVs2) {
  33146. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33147. }
  33148. if (parsedMesh.hasUVs3) {
  33149. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33150. }
  33151. if (parsedMesh.hasUVs4) {
  33152. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33153. }
  33154. if (parsedMesh.hasUVs5) {
  33155. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33156. }
  33157. if (parsedMesh.hasUVs6) {
  33158. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33159. }
  33160. if (parsedMesh.hasColors) {
  33161. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33162. }
  33163. if (parsedMesh.hasMatricesIndices) {
  33164. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33165. }
  33166. if (parsedMesh.hasMatricesWeights) {
  33167. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33168. }
  33169. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33170. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33171. mesh._checkDelayState();
  33172. }
  33173. }
  33174. else {
  33175. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33176. }
  33177. // Material
  33178. if (parsedMesh.materialId) {
  33179. mesh.setMaterialByID(parsedMesh.materialId);
  33180. }
  33181. else {
  33182. mesh.material = null;
  33183. }
  33184. // Morph targets
  33185. if (parsedMesh.morphTargetManagerId > -1) {
  33186. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33187. }
  33188. // Skeleton
  33189. if (parsedMesh.skeletonId > -1) {
  33190. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33191. if (parsedMesh.numBoneInfluencers) {
  33192. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33193. }
  33194. }
  33195. // Animations
  33196. if (parsedMesh.animations) {
  33197. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33198. var parsedAnimation = parsedMesh.animations[animationIndex];
  33199. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33200. }
  33201. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33202. }
  33203. if (parsedMesh.autoAnimate) {
  33204. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33205. }
  33206. // Layer Mask
  33207. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33208. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33209. }
  33210. else {
  33211. mesh.layerMask = 0x0FFFFFFF;
  33212. }
  33213. // Physics
  33214. if (parsedMesh.physicsImpostor) {
  33215. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33216. mass: parsedMesh.physicsMass,
  33217. friction: parsedMesh.physicsFriction,
  33218. restitution: parsedMesh.physicsRestitution
  33219. }, scene);
  33220. }
  33221. // Instances
  33222. if (parsedMesh.instances) {
  33223. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33224. var parsedInstance = parsedMesh.instances[index];
  33225. var instance = mesh.createInstance(parsedInstance.name);
  33226. if (parsedInstance.id) {
  33227. instance.id = parsedInstance.id;
  33228. }
  33229. if (BABYLON.Tags) {
  33230. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33231. }
  33232. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33233. if (parsedInstance.parentId) {
  33234. instance._waitingParentId = parsedInstance.parentId;
  33235. }
  33236. if (parsedInstance.rotationQuaternion) {
  33237. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33238. }
  33239. else if (parsedInstance.rotation) {
  33240. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33241. }
  33242. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33243. instance.checkCollisions = mesh.checkCollisions;
  33244. if (parsedMesh.animations) {
  33245. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33246. parsedAnimation = parsedMesh.animations[animationIndex];
  33247. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33248. }
  33249. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33250. }
  33251. }
  33252. }
  33253. return mesh;
  33254. };
  33255. /**
  33256. * Creates a ribbon mesh.
  33257. * Please consider using the same method from the MeshBuilder class instead.
  33258. * 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.
  33259. *
  33260. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33261. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33262. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33263. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33264. * 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.
  33265. * 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.
  33266. * 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
  33267. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33268. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33269. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33270. */
  33271. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33272. if (closeArray === void 0) { closeArray = false; }
  33273. if (updatable === void 0) { updatable = false; }
  33274. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33275. pathArray: pathArray,
  33276. closeArray: closeArray,
  33277. closePath: closePath,
  33278. offset: offset,
  33279. updatable: updatable,
  33280. sideOrientation: sideOrientation,
  33281. instance: instance
  33282. }, scene);
  33283. };
  33284. /**
  33285. * Creates a plane polygonal mesh. By default, this is a disc.
  33286. * Please consider using the same method from the MeshBuilder class instead.
  33287. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33288. * 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.
  33289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33290. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33292. */
  33293. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33294. if (scene === void 0) { scene = null; }
  33295. var options = {
  33296. radius: radius,
  33297. tessellation: tessellation,
  33298. sideOrientation: sideOrientation,
  33299. updatable: updatable
  33300. };
  33301. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33302. };
  33303. /**
  33304. * Creates a box mesh.
  33305. * Please consider using the same method from the MeshBuilder class instead.
  33306. * The parameter `size` sets the size (float) of each box side (default 1).
  33307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33308. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33310. */
  33311. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33312. if (scene === void 0) { scene = null; }
  33313. var options = {
  33314. size: size,
  33315. sideOrientation: sideOrientation,
  33316. updatable: updatable
  33317. };
  33318. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33319. };
  33320. /**
  33321. * Creates a sphere mesh.
  33322. * Please consider using the same method from the MeshBuilder class instead.
  33323. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33324. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33325. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33326. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33327. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33328. */
  33329. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33330. var options = {
  33331. segments: segments,
  33332. diameterX: diameter,
  33333. diameterY: diameter,
  33334. diameterZ: diameter,
  33335. sideOrientation: sideOrientation,
  33336. updatable: updatable
  33337. };
  33338. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33339. };
  33340. /**
  33341. * Creates a cylinder or a cone mesh.
  33342. * Please consider using the same method from the MeshBuilder class instead.
  33343. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33344. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33345. * 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.
  33346. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33347. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33348. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33349. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33350. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33351. */
  33352. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33353. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33354. if (scene !== undefined) {
  33355. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33356. updatable = scene;
  33357. }
  33358. scene = subdivisions;
  33359. subdivisions = 1;
  33360. }
  33361. var options = {
  33362. height: height,
  33363. diameterTop: diameterTop,
  33364. diameterBottom: diameterBottom,
  33365. tessellation: tessellation,
  33366. subdivisions: subdivisions,
  33367. sideOrientation: sideOrientation,
  33368. updatable: updatable
  33369. };
  33370. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33371. };
  33372. // Torus (Code from SharpDX.org)
  33373. /**
  33374. * Creates a torus mesh.
  33375. * Please consider using the same method from the MeshBuilder class instead.
  33376. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33377. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33378. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33379. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33380. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33381. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33382. */
  33383. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33384. var options = {
  33385. diameter: diameter,
  33386. thickness: thickness,
  33387. tessellation: tessellation,
  33388. sideOrientation: sideOrientation,
  33389. updatable: updatable
  33390. };
  33391. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33392. };
  33393. /**
  33394. * Creates a torus knot mesh.
  33395. * Please consider using the same method from the MeshBuilder class instead.
  33396. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33397. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33398. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33399. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33400. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33401. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33402. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33403. */
  33404. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33405. var options = {
  33406. radius: radius,
  33407. tube: tube,
  33408. radialSegments: radialSegments,
  33409. tubularSegments: tubularSegments,
  33410. p: p,
  33411. q: q,
  33412. sideOrientation: sideOrientation,
  33413. updatable: updatable
  33414. };
  33415. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33416. };
  33417. /**
  33418. * Creates a line mesh.
  33419. * Please consider using the same method from the MeshBuilder class instead.
  33420. * 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.
  33421. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33422. * The parameter `points` is an array successive Vector3.
  33423. * 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
  33424. * When updating an instance, remember that only point positions can change, not the number of points.
  33425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33426. */
  33427. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33428. if (scene === void 0) { scene = null; }
  33429. if (updatable === void 0) { updatable = false; }
  33430. if (instance === void 0) { instance = null; }
  33431. var options = {
  33432. points: points,
  33433. updatable: updatable,
  33434. instance: instance
  33435. };
  33436. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33437. };
  33438. /**
  33439. * Creates a dashed line mesh.
  33440. * Please consider using the same method from the MeshBuilder class instead.
  33441. * 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.
  33442. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33443. * The parameter `points` is an array successive Vector3.
  33444. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33445. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33446. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33447. * 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
  33448. * When updating an instance, remember that only point positions can change, not the number of points.
  33449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33450. */
  33451. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33452. if (scene === void 0) { scene = null; }
  33453. var options = {
  33454. points: points,
  33455. dashSize: dashSize,
  33456. gapSize: gapSize,
  33457. dashNb: dashNb,
  33458. updatable: updatable,
  33459. instance: instance
  33460. };
  33461. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33462. };
  33463. /**
  33464. * Creates a polygon mesh.
  33465. * Please consider using the same method from the MeshBuilder class instead.
  33466. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33467. * 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.
  33468. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33470. * Remember you can only change the shape positions, not their number when updating a polygon.
  33471. */
  33472. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33473. var options = {
  33474. shape: shape,
  33475. holes: holes,
  33476. updatable: updatable,
  33477. sideOrientation: sideOrientation
  33478. };
  33479. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33480. };
  33481. /**
  33482. * Creates an extruded polygon mesh, with depth in the Y direction.
  33483. * Please consider using the same method from the MeshBuilder class instead.
  33484. */
  33485. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33486. var options = {
  33487. shape: shape,
  33488. holes: holes,
  33489. depth: depth,
  33490. updatable: updatable,
  33491. sideOrientation: sideOrientation
  33492. };
  33493. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33494. };
  33495. /**
  33496. * Creates an extruded shape mesh.
  33497. * 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.
  33498. * Please consider using the same method from the MeshBuilder class instead.
  33499. *
  33500. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33501. * 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
  33502. * extruded along the Z axis.
  33503. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33504. * 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.
  33505. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33506. * 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
  33507. * 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
  33508. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33509. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33510. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33512. */
  33513. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33514. if (scene === void 0) { scene = null; }
  33515. var options = {
  33516. shape: shape,
  33517. path: path,
  33518. scale: scale,
  33519. rotation: rotation,
  33520. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33521. sideOrientation: sideOrientation,
  33522. instance: instance,
  33523. updatable: updatable
  33524. };
  33525. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33526. };
  33527. /**
  33528. * Creates an custom extruded shape mesh.
  33529. * 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.
  33530. * Please consider using the same method from the MeshBuilder class instead.
  33531. *
  33532. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33533. * 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
  33534. * extruded along the Z axis.
  33535. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33536. * 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
  33537. * and the distance of this point from the begining of the path :
  33538. * ```javascript
  33539. * var rotationFunction = function(i, distance) {
  33540. * // do things
  33541. * return rotationValue; }
  33542. * ```
  33543. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33544. * 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
  33545. * and the distance of this point from the begining of the path :
  33546. * ```javascript
  33547. * var scaleFunction = function(i, distance) {
  33548. * // do things
  33549. * return scaleValue;}
  33550. * ```
  33551. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33552. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33553. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33554. * 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
  33555. * 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
  33556. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33558. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33560. */
  33561. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33562. var options = {
  33563. shape: shape,
  33564. path: path,
  33565. scaleFunction: scaleFunction,
  33566. rotationFunction: rotationFunction,
  33567. ribbonCloseArray: ribbonCloseArray,
  33568. ribbonClosePath: ribbonClosePath,
  33569. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33570. sideOrientation: sideOrientation,
  33571. instance: instance,
  33572. updatable: updatable
  33573. };
  33574. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33575. };
  33576. /**
  33577. * Creates lathe mesh.
  33578. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33579. * Please consider using the same method from the MeshBuilder class instead.
  33580. * 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
  33581. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33582. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33583. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33585. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33586. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33587. */
  33588. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33589. var options = {
  33590. shape: shape,
  33591. radius: radius,
  33592. tessellation: tessellation,
  33593. sideOrientation: sideOrientation,
  33594. updatable: updatable
  33595. };
  33596. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33597. };
  33598. /**
  33599. * Creates a plane mesh.
  33600. * Please consider using the same method from the MeshBuilder class instead.
  33601. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33603. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33605. */
  33606. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33607. var options = {
  33608. size: size,
  33609. width: size,
  33610. height: size,
  33611. sideOrientation: sideOrientation,
  33612. updatable: updatable
  33613. };
  33614. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33615. };
  33616. /**
  33617. * Creates a ground mesh.
  33618. * Please consider using the same method from the MeshBuilder class instead.
  33619. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33620. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33622. */
  33623. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33624. var options = {
  33625. width: width,
  33626. height: height,
  33627. subdivisions: subdivisions,
  33628. updatable: updatable
  33629. };
  33630. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33631. };
  33632. /**
  33633. * Creates a tiled ground mesh.
  33634. * Please consider using the same method from the MeshBuilder class instead.
  33635. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33636. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33637. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33638. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33639. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33640. * numbers of subdivisions on the ground width and height of each tile.
  33641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33642. */
  33643. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33644. var options = {
  33645. xmin: xmin,
  33646. zmin: zmin,
  33647. xmax: xmax,
  33648. zmax: zmax,
  33649. subdivisions: subdivisions,
  33650. precision: precision,
  33651. updatable: updatable
  33652. };
  33653. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33654. };
  33655. /**
  33656. * Creates a ground mesh from a height map.
  33657. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33658. * Please consider using the same method from the MeshBuilder class instead.
  33659. * The parameter `url` sets the URL of the height map image resource.
  33660. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33661. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33662. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33663. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33664. * 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).
  33665. * This function is passed the newly built mesh :
  33666. * ```javascript
  33667. * function(mesh) { // do things
  33668. * return; }
  33669. * ```
  33670. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33671. */
  33672. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33673. var options = {
  33674. width: width,
  33675. height: height,
  33676. subdivisions: subdivisions,
  33677. minHeight: minHeight,
  33678. maxHeight: maxHeight,
  33679. updatable: updatable,
  33680. onReady: onReady
  33681. };
  33682. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33683. };
  33684. /**
  33685. * Creates a tube mesh.
  33686. * 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.
  33687. * Please consider using the same method from the MeshBuilder class instead.
  33688. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33689. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33690. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33691. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33692. * 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.
  33693. * It must return a radius value (positive float) :
  33694. * ```javascript
  33695. * var radiusFunction = function(i, distance) {
  33696. * // do things
  33697. * return radius; }
  33698. * ```
  33699. * 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
  33700. * 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
  33701. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33702. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33703. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33704. */
  33705. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33706. var options = {
  33707. path: path,
  33708. radius: radius,
  33709. tessellation: tessellation,
  33710. radiusFunction: radiusFunction,
  33711. arc: 1,
  33712. cap: cap,
  33713. updatable: updatable,
  33714. sideOrientation: sideOrientation,
  33715. instance: instance
  33716. };
  33717. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33718. };
  33719. /**
  33720. * Creates a polyhedron mesh.
  33721. * Please consider using the same method from the MeshBuilder class instead.
  33722. * 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
  33723. * to choose the wanted type.
  33724. * The parameter `size` (positive float, default 1) sets the polygon size.
  33725. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33726. * 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`.
  33727. * 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
  33728. * 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)`).
  33729. * 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
  33730. * 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.
  33731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33732. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33734. */
  33735. Mesh.CreatePolyhedron = function (name, options, scene) {
  33736. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33737. };
  33738. /**
  33739. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33740. * Please consider using the same method from the MeshBuilder class instead.
  33741. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33742. * 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`).
  33743. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33744. * 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.
  33745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33746. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33747. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33748. */
  33749. Mesh.CreateIcoSphere = function (name, options, scene) {
  33750. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33751. };
  33752. /**
  33753. * Creates a decal mesh.
  33754. * Please consider using the same method from the MeshBuilder class instead.
  33755. * 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.
  33756. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33757. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33758. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33759. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33760. */
  33761. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33762. var options = {
  33763. position: position,
  33764. normal: normal,
  33765. size: size,
  33766. angle: angle
  33767. };
  33768. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33769. };
  33770. // Skeletons
  33771. /**
  33772. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33773. */
  33774. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33775. if (!this._sourcePositions) {
  33776. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33777. if (!source) {
  33778. return this._sourcePositions;
  33779. }
  33780. this._sourcePositions = new Float32Array(source);
  33781. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33782. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33783. }
  33784. }
  33785. return this._sourcePositions;
  33786. };
  33787. /**
  33788. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33789. */
  33790. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33791. if (!this._sourceNormals) {
  33792. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33793. if (!source) {
  33794. return this._sourceNormals;
  33795. }
  33796. this._sourceNormals = new Float32Array(source);
  33797. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33798. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33799. }
  33800. }
  33801. return this._sourceNormals;
  33802. };
  33803. /**
  33804. * Updates the vertex buffer by applying transformation from the bones.
  33805. * Returns the Mesh.
  33806. *
  33807. * @param {skeleton} skeleton to apply
  33808. */
  33809. Mesh.prototype.applySkeleton = function (skeleton) {
  33810. if (!this.geometry) {
  33811. return this;
  33812. }
  33813. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33814. return this;
  33815. }
  33816. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33817. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33818. return this;
  33819. }
  33820. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33821. return this;
  33822. }
  33823. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33824. return this;
  33825. }
  33826. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33827. return this;
  33828. }
  33829. if (!this._sourcePositions) {
  33830. var submeshes = this.subMeshes.slice();
  33831. this.setPositionsForCPUSkinning();
  33832. this.subMeshes = submeshes;
  33833. }
  33834. if (!this._sourceNormals) {
  33835. this.setNormalsForCPUSkinning();
  33836. }
  33837. // positionsData checks for not being Float32Array will only pass at most once
  33838. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33839. if (!positionsData) {
  33840. return this;
  33841. }
  33842. if (!(positionsData instanceof Float32Array)) {
  33843. positionsData = new Float32Array(positionsData);
  33844. }
  33845. // normalsData checks for not being Float32Array will only pass at most once
  33846. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33847. if (!normalsData) {
  33848. return this;
  33849. }
  33850. if (!(normalsData instanceof Float32Array)) {
  33851. normalsData = new Float32Array(normalsData);
  33852. }
  33853. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33854. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33855. if (!matricesWeightsData || !matricesIndicesData) {
  33856. return this;
  33857. }
  33858. var needExtras = this.numBoneInfluencers > 4;
  33859. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33860. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33861. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33862. var tempVector3 = BABYLON.Vector3.Zero();
  33863. var finalMatrix = new BABYLON.Matrix();
  33864. var tempMatrix = new BABYLON.Matrix();
  33865. var matWeightIdx = 0;
  33866. var inf;
  33867. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33868. var weight;
  33869. for (inf = 0; inf < 4; inf++) {
  33870. weight = matricesWeightsData[matWeightIdx + inf];
  33871. if (weight > 0) {
  33872. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33873. finalMatrix.addToSelf(tempMatrix);
  33874. }
  33875. else
  33876. break;
  33877. }
  33878. if (needExtras) {
  33879. for (inf = 0; inf < 4; inf++) {
  33880. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33881. if (weight > 0) {
  33882. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33883. finalMatrix.addToSelf(tempMatrix);
  33884. }
  33885. else
  33886. break;
  33887. }
  33888. }
  33889. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33890. tempVector3.toArray(positionsData, index);
  33891. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33892. tempVector3.toArray(normalsData, index);
  33893. finalMatrix.reset();
  33894. }
  33895. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33896. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33897. return this;
  33898. };
  33899. // Tools
  33900. /**
  33901. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33902. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33903. */
  33904. Mesh.MinMax = function (meshes) {
  33905. var minVector = null;
  33906. var maxVector = null;
  33907. meshes.forEach(function (mesh, index, array) {
  33908. var boundingInfo = mesh.getBoundingInfo();
  33909. var boundingBox = boundingInfo.boundingBox;
  33910. if (!minVector || !maxVector) {
  33911. minVector = boundingBox.minimumWorld;
  33912. maxVector = boundingBox.maximumWorld;
  33913. }
  33914. else {
  33915. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33916. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33917. }
  33918. });
  33919. if (!minVector || !maxVector) {
  33920. return {
  33921. min: BABYLON.Vector3.Zero(),
  33922. max: BABYLON.Vector3.Zero()
  33923. };
  33924. }
  33925. return {
  33926. min: minVector,
  33927. max: maxVector
  33928. };
  33929. };
  33930. /**
  33931. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33932. */
  33933. Mesh.Center = function (meshesOrMinMaxVector) {
  33934. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33935. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33936. };
  33937. /**
  33938. * Merge the array of meshes into a single mesh for performance reasons.
  33939. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33940. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33941. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33942. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33943. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33944. */
  33945. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33946. if (disposeSource === void 0) { disposeSource = true; }
  33947. var index;
  33948. if (!allow32BitsIndices) {
  33949. var totalVertices = 0;
  33950. // Counting vertices
  33951. for (index = 0; index < meshes.length; index++) {
  33952. if (meshes[index]) {
  33953. totalVertices += meshes[index].getTotalVertices();
  33954. if (totalVertices > 65536) {
  33955. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33956. return null;
  33957. }
  33958. }
  33959. }
  33960. }
  33961. // Merge
  33962. var vertexData = null;
  33963. var otherVertexData;
  33964. var indiceArray = new Array();
  33965. var source = null;
  33966. for (index = 0; index < meshes.length; index++) {
  33967. if (meshes[index]) {
  33968. meshes[index].computeWorldMatrix(true);
  33969. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33970. otherVertexData.transform(meshes[index].getWorldMatrix());
  33971. if (vertexData) {
  33972. vertexData.merge(otherVertexData);
  33973. }
  33974. else {
  33975. vertexData = otherVertexData;
  33976. source = meshes[index];
  33977. }
  33978. if (subdivideWithSubMeshes) {
  33979. indiceArray.push(meshes[index].getTotalIndices());
  33980. }
  33981. }
  33982. }
  33983. source = source;
  33984. if (!meshSubclass) {
  33985. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33986. }
  33987. vertexData.applyToMesh(meshSubclass);
  33988. // Setting properties
  33989. meshSubclass.material = source.material;
  33990. meshSubclass.checkCollisions = source.checkCollisions;
  33991. // Cleaning
  33992. if (disposeSource) {
  33993. for (index = 0; index < meshes.length; index++) {
  33994. if (meshes[index]) {
  33995. meshes[index].dispose();
  33996. }
  33997. }
  33998. }
  33999. // Subdivide
  34000. if (subdivideWithSubMeshes) {
  34001. //-- Suppresions du submesh global
  34002. meshSubclass.releaseSubMeshes();
  34003. index = 0;
  34004. var offset = 0;
  34005. //-- aplique la subdivision en fonction du tableau d'indices
  34006. while (index < indiceArray.length) {
  34007. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34008. offset += indiceArray[index];
  34009. index++;
  34010. }
  34011. }
  34012. return meshSubclass;
  34013. };
  34014. // Consts
  34015. Mesh._FRONTSIDE = 0;
  34016. Mesh._BACKSIDE = 1;
  34017. Mesh._DOUBLESIDE = 2;
  34018. Mesh._DEFAULTSIDE = 0;
  34019. Mesh._NO_CAP = 0;
  34020. Mesh._CAP_START = 1;
  34021. Mesh._CAP_END = 2;
  34022. Mesh._CAP_ALL = 3;
  34023. return Mesh;
  34024. }(BABYLON.AbstractMesh));
  34025. BABYLON.Mesh = Mesh;
  34026. })(BABYLON || (BABYLON = {}));
  34027. //# sourceMappingURL=babylon.mesh.js.map
  34028. var BABYLON;
  34029. (function (BABYLON) {
  34030. var BaseSubMesh = /** @class */ (function () {
  34031. function BaseSubMesh() {
  34032. }
  34033. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34034. get: function () {
  34035. return this._materialEffect;
  34036. },
  34037. enumerable: true,
  34038. configurable: true
  34039. });
  34040. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34041. if (defines === void 0) { defines = null; }
  34042. if (this._materialEffect === effect) {
  34043. if (!effect) {
  34044. this._materialDefines = null;
  34045. }
  34046. return;
  34047. }
  34048. this._materialDefines = defines;
  34049. this._materialEffect = effect;
  34050. };
  34051. return BaseSubMesh;
  34052. }());
  34053. BABYLON.BaseSubMesh = BaseSubMesh;
  34054. var SubMesh = /** @class */ (function (_super) {
  34055. __extends(SubMesh, _super);
  34056. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34057. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34058. var _this = _super.call(this) || this;
  34059. _this.materialIndex = materialIndex;
  34060. _this.verticesStart = verticesStart;
  34061. _this.verticesCount = verticesCount;
  34062. _this.indexStart = indexStart;
  34063. _this.indexCount = indexCount;
  34064. _this._renderId = 0;
  34065. _this._mesh = mesh;
  34066. _this._renderingMesh = renderingMesh || mesh;
  34067. mesh.subMeshes.push(_this);
  34068. _this._trianglePlanes = [];
  34069. _this._id = mesh.subMeshes.length - 1;
  34070. if (createBoundingBox) {
  34071. _this.refreshBoundingInfo();
  34072. mesh.computeWorldMatrix(true);
  34073. }
  34074. return _this;
  34075. }
  34076. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34077. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34078. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34079. };
  34080. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34081. get: function () {
  34082. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34083. },
  34084. enumerable: true,
  34085. configurable: true
  34086. });
  34087. /**
  34088. * Returns the submesh BoudingInfo object.
  34089. */
  34090. SubMesh.prototype.getBoundingInfo = function () {
  34091. if (this.IsGlobal) {
  34092. return this._mesh.getBoundingInfo();
  34093. }
  34094. return this._boundingInfo;
  34095. };
  34096. /**
  34097. * Sets the submesh BoundingInfo.
  34098. * Return the SubMesh.
  34099. */
  34100. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34101. this._boundingInfo = boundingInfo;
  34102. return this;
  34103. };
  34104. /**
  34105. * Returns the mesh of the current submesh.
  34106. */
  34107. SubMesh.prototype.getMesh = function () {
  34108. return this._mesh;
  34109. };
  34110. /**
  34111. * Returns the rendering mesh of the submesh.
  34112. */
  34113. SubMesh.prototype.getRenderingMesh = function () {
  34114. return this._renderingMesh;
  34115. };
  34116. /**
  34117. * Returns the submesh material.
  34118. */
  34119. SubMesh.prototype.getMaterial = function () {
  34120. var rootMaterial = this._renderingMesh.material;
  34121. if (rootMaterial === null || rootMaterial === undefined) {
  34122. return this._mesh.getScene().defaultMaterial;
  34123. }
  34124. else if (rootMaterial.getSubMaterial) {
  34125. var multiMaterial = rootMaterial;
  34126. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34127. if (this._currentMaterial !== effectiveMaterial) {
  34128. this._currentMaterial = effectiveMaterial;
  34129. this._materialDefines = null;
  34130. }
  34131. return effectiveMaterial;
  34132. }
  34133. return rootMaterial;
  34134. };
  34135. // Methods
  34136. /**
  34137. * Sets a new updated BoundingInfo object to the submesh.
  34138. * Returns the SubMesh.
  34139. */
  34140. SubMesh.prototype.refreshBoundingInfo = function () {
  34141. this._lastColliderWorldVertices = null;
  34142. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34143. return this;
  34144. }
  34145. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34146. if (!data) {
  34147. this._boundingInfo = this._mesh.getBoundingInfo();
  34148. return this;
  34149. }
  34150. var indices = this._renderingMesh.getIndices();
  34151. var extend;
  34152. //is this the only submesh?
  34153. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34154. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34155. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34156. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34157. }
  34158. else {
  34159. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34160. }
  34161. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34162. return this;
  34163. };
  34164. SubMesh.prototype._checkCollision = function (collider) {
  34165. var boundingInfo = this.getBoundingInfo();
  34166. return boundingInfo._checkCollision(collider);
  34167. };
  34168. /**
  34169. * Updates the submesh BoundingInfo.
  34170. * Returns the Submesh.
  34171. */
  34172. SubMesh.prototype.updateBoundingInfo = function (world) {
  34173. var boundingInfo = this.getBoundingInfo();
  34174. if (!boundingInfo) {
  34175. this.refreshBoundingInfo();
  34176. boundingInfo = this.getBoundingInfo();
  34177. }
  34178. boundingInfo.update(world);
  34179. return this;
  34180. };
  34181. /**
  34182. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34183. * Boolean returned.
  34184. */
  34185. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34186. var boundingInfo = this.getBoundingInfo();
  34187. if (!boundingInfo) {
  34188. return false;
  34189. }
  34190. return boundingInfo.isInFrustum(frustumPlanes);
  34191. };
  34192. /**
  34193. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34194. * Boolean returned.
  34195. */
  34196. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34197. var boundingInfo = this.getBoundingInfo();
  34198. if (!boundingInfo) {
  34199. return false;
  34200. }
  34201. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34202. };
  34203. /**
  34204. * Renders the submesh.
  34205. * Returns it.
  34206. */
  34207. SubMesh.prototype.render = function (enableAlphaMode) {
  34208. this._renderingMesh.render(this, enableAlphaMode);
  34209. return this;
  34210. };
  34211. /**
  34212. * Returns a new Index Buffer.
  34213. * Type returned : WebGLBuffer.
  34214. */
  34215. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34216. if (!this._linesIndexBuffer) {
  34217. var linesIndices = [];
  34218. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34219. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34220. }
  34221. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34222. this.linesIndexCount = linesIndices.length;
  34223. }
  34224. return this._linesIndexBuffer;
  34225. };
  34226. /**
  34227. * True is the passed Ray intersects the submesh bounding box.
  34228. * Boolean returned.
  34229. */
  34230. SubMesh.prototype.canIntersects = function (ray) {
  34231. var boundingInfo = this.getBoundingInfo();
  34232. if (!boundingInfo) {
  34233. return false;
  34234. }
  34235. return ray.intersectsBox(boundingInfo.boundingBox);
  34236. };
  34237. /**
  34238. * Returns an object IntersectionInfo.
  34239. */
  34240. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34241. var intersectInfo = null;
  34242. var material = this.getMaterial();
  34243. if (!material) {
  34244. return null;
  34245. }
  34246. switch (material.fillMode) {
  34247. case BABYLON.Material.PointListDrawMode:
  34248. case BABYLON.Material.LineListDrawMode:
  34249. case BABYLON.Material.LineLoopDrawMode:
  34250. case BABYLON.Material.LineStripDrawMode:
  34251. case BABYLON.Material.TriangleFanDrawMode:
  34252. case BABYLON.Material.TriangleStripDrawMode:
  34253. return null;
  34254. }
  34255. // LineMesh first as it's also a Mesh...
  34256. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34257. var lineMesh = this._mesh;
  34258. // Line test
  34259. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34260. var p0 = positions[indices[index]];
  34261. var p1 = positions[indices[index + 1]];
  34262. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34263. if (length < 0) {
  34264. continue;
  34265. }
  34266. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34267. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34268. if (fastCheck) {
  34269. break;
  34270. }
  34271. }
  34272. }
  34273. }
  34274. else {
  34275. // Triangles test
  34276. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34277. var p0 = positions[indices[index]];
  34278. var p1 = positions[indices[index + 1]];
  34279. var p2 = positions[indices[index + 2]];
  34280. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34281. if (currentIntersectInfo) {
  34282. if (currentIntersectInfo.distance < 0) {
  34283. continue;
  34284. }
  34285. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34286. intersectInfo = currentIntersectInfo;
  34287. intersectInfo.faceId = index / 3;
  34288. if (fastCheck) {
  34289. break;
  34290. }
  34291. }
  34292. }
  34293. }
  34294. }
  34295. return intersectInfo;
  34296. };
  34297. SubMesh.prototype._rebuild = function () {
  34298. if (this._linesIndexBuffer) {
  34299. this._linesIndexBuffer = null;
  34300. }
  34301. };
  34302. // Clone
  34303. /**
  34304. * Creates a new Submesh from the passed Mesh.
  34305. */
  34306. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34307. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34308. if (!this.IsGlobal) {
  34309. var boundingInfo = this.getBoundingInfo();
  34310. if (!boundingInfo) {
  34311. return result;
  34312. }
  34313. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34314. }
  34315. return result;
  34316. };
  34317. // Dispose
  34318. /**
  34319. * Disposes the Submesh.
  34320. * Returns nothing.
  34321. */
  34322. SubMesh.prototype.dispose = function () {
  34323. if (this._linesIndexBuffer) {
  34324. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34325. this._linesIndexBuffer = null;
  34326. }
  34327. // Remove from mesh
  34328. var index = this._mesh.subMeshes.indexOf(this);
  34329. this._mesh.subMeshes.splice(index, 1);
  34330. };
  34331. // Statics
  34332. /**
  34333. * Creates a new Submesh from the passed parameters :
  34334. * - materialIndex (integer) : the index of the main mesh material.
  34335. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34336. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34337. * - mesh (Mesh) : the main mesh to create the submesh from.
  34338. * - renderingMesh (optional Mesh) : rendering mesh.
  34339. */
  34340. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34341. var minVertexIndex = Number.MAX_VALUE;
  34342. var maxVertexIndex = -Number.MAX_VALUE;
  34343. renderingMesh = (renderingMesh || mesh);
  34344. var indices = renderingMesh.getIndices();
  34345. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34346. var vertexIndex = indices[index];
  34347. if (vertexIndex < minVertexIndex)
  34348. minVertexIndex = vertexIndex;
  34349. if (vertexIndex > maxVertexIndex)
  34350. maxVertexIndex = vertexIndex;
  34351. }
  34352. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34353. };
  34354. return SubMesh;
  34355. }(BaseSubMesh));
  34356. BABYLON.SubMesh = SubMesh;
  34357. })(BABYLON || (BABYLON = {}));
  34358. //# sourceMappingURL=babylon.subMesh.js.map
  34359. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34360. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34361. s = arguments[i];
  34362. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34363. t[p] = s[p];
  34364. }
  34365. return t;
  34366. };
  34367. var BABYLON;
  34368. (function (BABYLON) {
  34369. /**
  34370. * Manages the defines for the Material
  34371. */
  34372. var MaterialDefines = /** @class */ (function () {
  34373. function MaterialDefines() {
  34374. this._isDirty = true;
  34375. /** @hidden */
  34376. this._areLightsDirty = true;
  34377. /** @hidden */
  34378. this._areAttributesDirty = true;
  34379. /** @hidden */
  34380. this._areTexturesDirty = true;
  34381. /** @hidden */
  34382. this._areFresnelDirty = true;
  34383. /** @hidden */
  34384. this._areMiscDirty = true;
  34385. /** @hidden */
  34386. this._areImageProcessingDirty = true;
  34387. /** @hidden */
  34388. this._normals = false;
  34389. /** @hidden */
  34390. this._uvs = false;
  34391. /** @hidden */
  34392. this._needNormals = false;
  34393. /** @hidden */
  34394. this._needUVs = false;
  34395. }
  34396. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34397. /**
  34398. * Specifies if the material needs to be re-calculated
  34399. */
  34400. get: function () {
  34401. return this._isDirty;
  34402. },
  34403. enumerable: true,
  34404. configurable: true
  34405. });
  34406. /**
  34407. * Marks the material to indicate that it has been re-calculated
  34408. */
  34409. MaterialDefines.prototype.markAsProcessed = function () {
  34410. this._isDirty = false;
  34411. this._areAttributesDirty = false;
  34412. this._areTexturesDirty = false;
  34413. this._areFresnelDirty = false;
  34414. this._areLightsDirty = false;
  34415. this._areMiscDirty = false;
  34416. this._areImageProcessingDirty = false;
  34417. };
  34418. /**
  34419. * Marks the material to indicate that it needs to be re-calculated
  34420. */
  34421. MaterialDefines.prototype.markAsUnprocessed = function () {
  34422. this._isDirty = true;
  34423. };
  34424. /**
  34425. * Marks the material to indicate all of its defines need to be re-calculated
  34426. */
  34427. MaterialDefines.prototype.markAllAsDirty = function () {
  34428. this._areTexturesDirty = true;
  34429. this._areAttributesDirty = true;
  34430. this._areLightsDirty = true;
  34431. this._areFresnelDirty = true;
  34432. this._areMiscDirty = true;
  34433. this._areImageProcessingDirty = true;
  34434. this._isDirty = true;
  34435. };
  34436. /**
  34437. * Marks the material to indicate that image processing needs to be re-calculated
  34438. */
  34439. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34440. this._areImageProcessingDirty = true;
  34441. this._isDirty = true;
  34442. };
  34443. /**
  34444. * Marks the material to indicate the lights need to be re-calculated
  34445. */
  34446. MaterialDefines.prototype.markAsLightDirty = function () {
  34447. this._areLightsDirty = true;
  34448. this._isDirty = true;
  34449. };
  34450. /**
  34451. * Marks the attribute state as changed
  34452. */
  34453. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34454. this._areAttributesDirty = true;
  34455. this._isDirty = true;
  34456. };
  34457. /**
  34458. * Marks the texture state as changed
  34459. */
  34460. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34461. this._areTexturesDirty = true;
  34462. this._isDirty = true;
  34463. };
  34464. /**
  34465. * Marks the fresnel state as changed
  34466. */
  34467. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34468. this._areFresnelDirty = true;
  34469. this._isDirty = true;
  34470. };
  34471. /**
  34472. * Marks the misc state as changed
  34473. */
  34474. MaterialDefines.prototype.markAsMiscDirty = function () {
  34475. this._areMiscDirty = true;
  34476. this._isDirty = true;
  34477. };
  34478. /**
  34479. * Rebuilds the material defines
  34480. */
  34481. MaterialDefines.prototype.rebuild = function () {
  34482. if (this._keys) {
  34483. delete this._keys;
  34484. }
  34485. this._keys = [];
  34486. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34487. var key = _a[_i];
  34488. if (key[0] === "_") {
  34489. continue;
  34490. }
  34491. this._keys.push(key);
  34492. }
  34493. };
  34494. /**
  34495. * Specifies if two material defines are equal
  34496. * @param other - A material define instance to compare to
  34497. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34498. */
  34499. MaterialDefines.prototype.isEqual = function (other) {
  34500. if (this._keys.length !== other._keys.length) {
  34501. return false;
  34502. }
  34503. for (var index = 0; index < this._keys.length; index++) {
  34504. var prop = this._keys[index];
  34505. if (this[prop] !== other[prop]) {
  34506. return false;
  34507. }
  34508. }
  34509. return true;
  34510. };
  34511. /**
  34512. * Clones this instance's defines to another instance
  34513. * @param other - material defines to clone values to
  34514. */
  34515. MaterialDefines.prototype.cloneTo = function (other) {
  34516. if (this._keys.length !== other._keys.length) {
  34517. other._keys = this._keys.slice(0);
  34518. }
  34519. for (var index = 0; index < this._keys.length; index++) {
  34520. var prop = this._keys[index];
  34521. other[prop] = this[prop];
  34522. }
  34523. };
  34524. /**
  34525. * Resets the material define values
  34526. */
  34527. MaterialDefines.prototype.reset = function () {
  34528. for (var index = 0; index < this._keys.length; index++) {
  34529. var prop = this._keys[index];
  34530. var type = typeof this[prop];
  34531. switch (type) {
  34532. case "number":
  34533. this[prop] = 0;
  34534. break;
  34535. case "string":
  34536. this[prop] = "";
  34537. break;
  34538. default:
  34539. this[prop] = false;
  34540. break;
  34541. }
  34542. }
  34543. };
  34544. /**
  34545. * Converts the material define values to a string
  34546. * @returns - String of material define information
  34547. */
  34548. MaterialDefines.prototype.toString = function () {
  34549. var result = "";
  34550. for (var index = 0; index < this._keys.length; index++) {
  34551. var prop = this._keys[index];
  34552. var value = this[prop];
  34553. var type = typeof value;
  34554. switch (type) {
  34555. case "number":
  34556. case "string":
  34557. result += "#define " + prop + " " + value + "\n";
  34558. break;
  34559. default:
  34560. if (value) {
  34561. result += "#define " + prop + "\n";
  34562. }
  34563. break;
  34564. }
  34565. }
  34566. return result;
  34567. };
  34568. return MaterialDefines;
  34569. }());
  34570. BABYLON.MaterialDefines = MaterialDefines;
  34571. /**
  34572. * Base class for the main features of a material in Babylon.js
  34573. */
  34574. var Material = /** @class */ (function () {
  34575. /**
  34576. * Creates a material instance
  34577. * @param name defines the name of the material
  34578. * @param scene defines the scene to reference
  34579. * @param doNotAdd specifies if the material should be added to the scene
  34580. */
  34581. function Material(name, scene, doNotAdd) {
  34582. /**
  34583. * Specifies if the ready state should be checked on each call
  34584. */
  34585. this.checkReadyOnEveryCall = false;
  34586. /**
  34587. * Specifies if the ready state should be checked once
  34588. */
  34589. this.checkReadyOnlyOnce = false;
  34590. /**
  34591. * The state of the material
  34592. */
  34593. this.state = "";
  34594. /**
  34595. * The alpha value of the material
  34596. */
  34597. this._alpha = 1.0;
  34598. /**
  34599. * Specifies if back face culling is enabled
  34600. */
  34601. this._backFaceCulling = true;
  34602. /**
  34603. * Specifies if the material should be serialized
  34604. */
  34605. this.doNotSerialize = false;
  34606. /**
  34607. * Specifies if the effect should be stored on sub meshes
  34608. */
  34609. this.storeEffectOnSubMeshes = false;
  34610. /**
  34611. * An event triggered when the material is disposed
  34612. */
  34613. this.onDisposeObservable = new BABYLON.Observable();
  34614. /**
  34615. * An event triggered when the material is bound
  34616. */
  34617. this.onBindObservable = new BABYLON.Observable();
  34618. /**
  34619. * An event triggered when the material is unbound
  34620. */
  34621. this.onUnBindObservable = new BABYLON.Observable();
  34622. /**
  34623. * Stores the value of the alpha mode
  34624. */
  34625. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34626. /**
  34627. * Stores the state of the need depth pre-pass value
  34628. */
  34629. this._needDepthPrePass = false;
  34630. /**
  34631. * Specifies if depth writing should be disabled
  34632. */
  34633. this.disableDepthWrite = false;
  34634. /**
  34635. * Specifies if depth writing should be forced
  34636. */
  34637. this.forceDepthWrite = false;
  34638. /**
  34639. * Specifies if there should be a separate pass for culling
  34640. */
  34641. this.separateCullingPass = false;
  34642. /**
  34643. * Stores the state specifing if fog should be enabled
  34644. */
  34645. this._fogEnabled = true;
  34646. /**
  34647. * Stores the size of points
  34648. */
  34649. this.pointSize = 1.0;
  34650. /**
  34651. * Stores the z offset value
  34652. */
  34653. this.zOffset = 0;
  34654. /**
  34655. * Specifies if the material was previously ready
  34656. */
  34657. this._wasPreviouslyReady = false;
  34658. /**
  34659. * Stores the fill mode state
  34660. */
  34661. this._fillMode = Material.TriangleFillMode;
  34662. this.name = name;
  34663. this.id = name || BABYLON.Tools.RandomId();
  34664. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34665. if (this._scene.useRightHandedSystem) {
  34666. this.sideOrientation = Material.ClockWiseSideOrientation;
  34667. }
  34668. else {
  34669. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34670. }
  34671. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34672. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34673. if (!doNotAdd) {
  34674. this._scene.materials.push(this);
  34675. }
  34676. }
  34677. Object.defineProperty(Material, "TriangleFillMode", {
  34678. /**
  34679. * Returns the triangle fill mode
  34680. */
  34681. get: function () {
  34682. return Material._TriangleFillMode;
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. Object.defineProperty(Material, "WireFrameFillMode", {
  34688. /**
  34689. * Returns the wireframe mode
  34690. */
  34691. get: function () {
  34692. return Material._WireFrameFillMode;
  34693. },
  34694. enumerable: true,
  34695. configurable: true
  34696. });
  34697. Object.defineProperty(Material, "PointFillMode", {
  34698. /**
  34699. * Returns the point fill mode
  34700. */
  34701. get: function () {
  34702. return Material._PointFillMode;
  34703. },
  34704. enumerable: true,
  34705. configurable: true
  34706. });
  34707. Object.defineProperty(Material, "PointListDrawMode", {
  34708. /**
  34709. * Returns the point list draw mode
  34710. */
  34711. get: function () {
  34712. return Material._PointListDrawMode;
  34713. },
  34714. enumerable: true,
  34715. configurable: true
  34716. });
  34717. Object.defineProperty(Material, "LineListDrawMode", {
  34718. /**
  34719. * Returns the line list draw mode
  34720. */
  34721. get: function () {
  34722. return Material._LineListDrawMode;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. Object.defineProperty(Material, "LineLoopDrawMode", {
  34728. /**
  34729. * Returns the line loop draw mode
  34730. */
  34731. get: function () {
  34732. return Material._LineLoopDrawMode;
  34733. },
  34734. enumerable: true,
  34735. configurable: true
  34736. });
  34737. Object.defineProperty(Material, "LineStripDrawMode", {
  34738. /**
  34739. * Returns the line strip draw mode
  34740. */
  34741. get: function () {
  34742. return Material._LineStripDrawMode;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34748. /**
  34749. * Returns the triangle strip draw mode
  34750. */
  34751. get: function () {
  34752. return Material._TriangleStripDrawMode;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34758. /**
  34759. * Returns the triangle fan draw mode
  34760. */
  34761. get: function () {
  34762. return Material._TriangleFanDrawMode;
  34763. },
  34764. enumerable: true,
  34765. configurable: true
  34766. });
  34767. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34768. /**
  34769. * Returns the clock-wise side orientation
  34770. */
  34771. get: function () {
  34772. return Material._ClockWiseSideOrientation;
  34773. },
  34774. enumerable: true,
  34775. configurable: true
  34776. });
  34777. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34778. /**
  34779. * Returns the counter clock-wise side orientation
  34780. */
  34781. get: function () {
  34782. return Material._CounterClockWiseSideOrientation;
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material, "TextureDirtyFlag", {
  34788. /**
  34789. * Returns the dirty texture flag value
  34790. */
  34791. get: function () {
  34792. return Material._TextureDirtyFlag;
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(Material, "LightDirtyFlag", {
  34798. /**
  34799. * Returns the dirty light flag value
  34800. */
  34801. get: function () {
  34802. return Material._LightDirtyFlag;
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34808. /**
  34809. * Returns the dirty fresnel flag value
  34810. */
  34811. get: function () {
  34812. return Material._FresnelDirtyFlag;
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34818. /**
  34819. * Returns the dirty attributes flag value
  34820. */
  34821. get: function () {
  34822. return Material._AttributesDirtyFlag;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material, "MiscDirtyFlag", {
  34828. /**
  34829. * Returns the dirty misc flag value
  34830. */
  34831. get: function () {
  34832. return Material._MiscDirtyFlag;
  34833. },
  34834. enumerable: true,
  34835. configurable: true
  34836. });
  34837. Object.defineProperty(Material.prototype, "alpha", {
  34838. /**
  34839. * Gets the alpha value of the material
  34840. */
  34841. get: function () {
  34842. return this._alpha;
  34843. },
  34844. /**
  34845. * Sets the alpha value of the material
  34846. */
  34847. set: function (value) {
  34848. if (this._alpha === value) {
  34849. return;
  34850. }
  34851. this._alpha = value;
  34852. this.markAsDirty(Material.MiscDirtyFlag);
  34853. },
  34854. enumerable: true,
  34855. configurable: true
  34856. });
  34857. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34858. /**
  34859. * Gets the back-face culling state
  34860. */
  34861. get: function () {
  34862. return this._backFaceCulling;
  34863. },
  34864. /**
  34865. * Sets the back-face culling state
  34866. */
  34867. set: function (value) {
  34868. if (this._backFaceCulling === value) {
  34869. return;
  34870. }
  34871. this._backFaceCulling = value;
  34872. this.markAsDirty(Material.TextureDirtyFlag);
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(Material.prototype, "onDispose", {
  34878. /**
  34879. * Called during a dispose event
  34880. */
  34881. set: function (callback) {
  34882. if (this._onDisposeObserver) {
  34883. this.onDisposeObservable.remove(this._onDisposeObserver);
  34884. }
  34885. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34886. },
  34887. enumerable: true,
  34888. configurable: true
  34889. });
  34890. Object.defineProperty(Material.prototype, "onBind", {
  34891. /**
  34892. * Called during a bind event
  34893. */
  34894. set: function (callback) {
  34895. if (this._onBindObserver) {
  34896. this.onBindObservable.remove(this._onBindObserver);
  34897. }
  34898. this._onBindObserver = this.onBindObservable.add(callback);
  34899. },
  34900. enumerable: true,
  34901. configurable: true
  34902. });
  34903. Object.defineProperty(Material.prototype, "alphaMode", {
  34904. /**
  34905. * Gets the value of the alpha mode
  34906. */
  34907. get: function () {
  34908. return this._alphaMode;
  34909. },
  34910. /**
  34911. * Sets the value of the alpha mode.
  34912. *
  34913. * | Value | Type | Description |
  34914. * | --- | --- | --- |
  34915. * | 0 | ALPHA_DISABLE | |
  34916. * | 1 | ALPHA_ADD | |
  34917. * | 2 | ALPHA_COMBINE | |
  34918. * | 3 | ALPHA_SUBTRACT | |
  34919. * | 4 | ALPHA_MULTIPLY | |
  34920. * | 5 | ALPHA_MAXIMIZED | |
  34921. * | 6 | ALPHA_ONEONE | |
  34922. * | 7 | ALPHA_PREMULTIPLIED | |
  34923. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34924. * | 9 | ALPHA_INTERPOLATE | |
  34925. * | 10 | ALPHA_SCREENMODE | |
  34926. *
  34927. */
  34928. set: function (value) {
  34929. if (this._alphaMode === value) {
  34930. return;
  34931. }
  34932. this._alphaMode = value;
  34933. this.markAsDirty(Material.TextureDirtyFlag);
  34934. },
  34935. enumerable: true,
  34936. configurable: true
  34937. });
  34938. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34939. /**
  34940. * Gets the depth pre-pass value
  34941. */
  34942. get: function () {
  34943. return this._needDepthPrePass;
  34944. },
  34945. /**
  34946. * Sets the need depth pre-pass value
  34947. */
  34948. set: function (value) {
  34949. if (this._needDepthPrePass === value) {
  34950. return;
  34951. }
  34952. this._needDepthPrePass = value;
  34953. if (this._needDepthPrePass) {
  34954. this.checkReadyOnEveryCall = true;
  34955. }
  34956. },
  34957. enumerable: true,
  34958. configurable: true
  34959. });
  34960. Object.defineProperty(Material.prototype, "fogEnabled", {
  34961. /**
  34962. * Gets the value of the fog enabled state
  34963. */
  34964. get: function () {
  34965. return this._fogEnabled;
  34966. },
  34967. /**
  34968. * Sets the state for enabling fog
  34969. */
  34970. set: function (value) {
  34971. if (this._fogEnabled === value) {
  34972. return;
  34973. }
  34974. this._fogEnabled = value;
  34975. this.markAsDirty(Material.MiscDirtyFlag);
  34976. },
  34977. enumerable: true,
  34978. configurable: true
  34979. });
  34980. Object.defineProperty(Material.prototype, "wireframe", {
  34981. /**
  34982. * Gets a value specifying if wireframe mode is enabled
  34983. */
  34984. get: function () {
  34985. switch (this._fillMode) {
  34986. case Material.WireFrameFillMode:
  34987. case Material.LineListDrawMode:
  34988. case Material.LineLoopDrawMode:
  34989. case Material.LineStripDrawMode:
  34990. return true;
  34991. }
  34992. return this._scene.forceWireframe;
  34993. },
  34994. /**
  34995. * Sets the state of wireframe mode
  34996. */
  34997. set: function (value) {
  34998. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. Object.defineProperty(Material.prototype, "pointsCloud", {
  35004. /**
  35005. * Gets the value specifying if point clouds are enabled
  35006. */
  35007. get: function () {
  35008. switch (this._fillMode) {
  35009. case Material.PointFillMode:
  35010. case Material.PointListDrawMode:
  35011. return true;
  35012. }
  35013. return this._scene.forcePointsCloud;
  35014. },
  35015. /**
  35016. * Sets the state of point cloud mode
  35017. */
  35018. set: function (value) {
  35019. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35020. },
  35021. enumerable: true,
  35022. configurable: true
  35023. });
  35024. Object.defineProperty(Material.prototype, "fillMode", {
  35025. /**
  35026. * Gets the material fill mode
  35027. */
  35028. get: function () {
  35029. return this._fillMode;
  35030. },
  35031. /**
  35032. * Sets the material fill mode
  35033. */
  35034. set: function (value) {
  35035. if (this._fillMode === value) {
  35036. return;
  35037. }
  35038. this._fillMode = value;
  35039. this.markAsDirty(Material.MiscDirtyFlag);
  35040. },
  35041. enumerable: true,
  35042. configurable: true
  35043. });
  35044. /**
  35045. * Returns a string representation of the current material
  35046. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35047. * @returns a string with material information
  35048. */
  35049. Material.prototype.toString = function (fullDetails) {
  35050. var ret = "Name: " + this.name;
  35051. if (fullDetails) {
  35052. }
  35053. return ret;
  35054. };
  35055. /**
  35056. * Gets the class name of the material
  35057. * @returns a string with the class name of the material
  35058. */
  35059. Material.prototype.getClassName = function () {
  35060. return "Material";
  35061. };
  35062. Object.defineProperty(Material.prototype, "isFrozen", {
  35063. /**
  35064. * Specifies if updates for the material been locked
  35065. */
  35066. get: function () {
  35067. return this.checkReadyOnlyOnce;
  35068. },
  35069. enumerable: true,
  35070. configurable: true
  35071. });
  35072. /**
  35073. * Locks updates for the material
  35074. */
  35075. Material.prototype.freeze = function () {
  35076. this.checkReadyOnlyOnce = true;
  35077. };
  35078. /**
  35079. * Unlocks updates for the material
  35080. */
  35081. Material.prototype.unfreeze = function () {
  35082. this.checkReadyOnlyOnce = false;
  35083. };
  35084. /**
  35085. * Specifies if the material is ready to be used
  35086. * @param mesh defines the mesh to check
  35087. * @param useInstances specifies if instances should be used
  35088. * @returns a boolean indicating if the material is ready to be used
  35089. */
  35090. Material.prototype.isReady = function (mesh, useInstances) {
  35091. return true;
  35092. };
  35093. /**
  35094. * Specifies that the submesh is ready to be used
  35095. * @param mesh defines the mesh to check
  35096. * @param subMesh defines which submesh to check
  35097. * @param useInstances specifies that instances should be used
  35098. * @returns a boolean indicating that the submesh is ready or not
  35099. */
  35100. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35101. return false;
  35102. };
  35103. /**
  35104. * Returns the material effect
  35105. * @returns the effect associated with the material
  35106. */
  35107. Material.prototype.getEffect = function () {
  35108. return this._effect;
  35109. };
  35110. /**
  35111. * Returns the current scene
  35112. * @returns a Scene
  35113. */
  35114. Material.prototype.getScene = function () {
  35115. return this._scene;
  35116. };
  35117. /**
  35118. * Specifies if the material will require alpha blending
  35119. * @returns a boolean specifying if alpha blending is needed
  35120. */
  35121. Material.prototype.needAlphaBlending = function () {
  35122. return (this.alpha < 1.0);
  35123. };
  35124. /**
  35125. * Specifies if the mesh will require alpha blending
  35126. * @param mesh defines the mesh to check
  35127. * @returns a boolean specifying if alpha blending is needed for the mesh
  35128. */
  35129. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35130. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35131. };
  35132. /**
  35133. * Specifies if this material should be rendered in alpha test mode
  35134. * @returns a boolean specifying if an alpha test is needed.
  35135. */
  35136. Material.prototype.needAlphaTesting = function () {
  35137. return false;
  35138. };
  35139. /**
  35140. * Gets the texture used for the alpha test
  35141. * @returns the texture to use for alpha testing
  35142. */
  35143. Material.prototype.getAlphaTestTexture = function () {
  35144. return null;
  35145. };
  35146. /**
  35147. * Marks the material to indicate that it needs to be re-calculated
  35148. */
  35149. Material.prototype.markDirty = function () {
  35150. this._wasPreviouslyReady = false;
  35151. };
  35152. /** @hidden */
  35153. Material.prototype._preBind = function (effect, overrideOrientation) {
  35154. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35155. var engine = this._scene.getEngine();
  35156. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35157. var reverse = orientation === Material.ClockWiseSideOrientation;
  35158. engine.enableEffect(effect ? effect : this._effect);
  35159. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35160. return reverse;
  35161. };
  35162. /**
  35163. * Binds the material to the mesh
  35164. * @param world defines the world transformation matrix
  35165. * @param mesh defines the mesh to bind the material to
  35166. */
  35167. Material.prototype.bind = function (world, mesh) {
  35168. };
  35169. /**
  35170. * Binds the submesh to the material
  35171. * @param world defines the world transformation matrix
  35172. * @param mesh defines the mesh containing the submesh
  35173. * @param subMesh defines the submesh to bind the material to
  35174. */
  35175. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35176. };
  35177. /**
  35178. * Binds the world matrix to the material
  35179. * @param world defines the world transformation matrix
  35180. */
  35181. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35182. };
  35183. /**
  35184. * Binds the scene's uniform buffer to the effect.
  35185. * @param effect defines the effect to bind to the scene uniform buffer
  35186. * @param sceneUbo defines the uniform buffer storing scene data
  35187. */
  35188. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35189. sceneUbo.bindToEffect(effect, "Scene");
  35190. };
  35191. /**
  35192. * Binds the view matrix to the effect
  35193. * @param effect defines the effect to bind the view matrix to
  35194. */
  35195. Material.prototype.bindView = function (effect) {
  35196. if (!this._useUBO) {
  35197. effect.setMatrix("view", this.getScene().getViewMatrix());
  35198. }
  35199. else {
  35200. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35201. }
  35202. };
  35203. /**
  35204. * Binds the view projection matrix to the effect
  35205. * @param effect defines the effect to bind the view projection matrix to
  35206. */
  35207. Material.prototype.bindViewProjection = function (effect) {
  35208. if (!this._useUBO) {
  35209. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35210. }
  35211. else {
  35212. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35213. }
  35214. };
  35215. /**
  35216. * Specifies if material alpha testing should be turned on for the mesh
  35217. * @param mesh defines the mesh to check
  35218. */
  35219. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35220. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35221. };
  35222. /**
  35223. * Processes to execute after binding the material to a mesh
  35224. * @param mesh defines the rendered mesh
  35225. */
  35226. Material.prototype._afterBind = function (mesh) {
  35227. this._scene._cachedMaterial = this;
  35228. if (mesh) {
  35229. this._scene._cachedVisibility = mesh.visibility;
  35230. }
  35231. else {
  35232. this._scene._cachedVisibility = 1;
  35233. }
  35234. if (mesh) {
  35235. this.onBindObservable.notifyObservers(mesh);
  35236. }
  35237. if (this.disableDepthWrite) {
  35238. var engine = this._scene.getEngine();
  35239. this._cachedDepthWriteState = engine.getDepthWrite();
  35240. engine.setDepthWrite(false);
  35241. }
  35242. };
  35243. /**
  35244. * Unbinds the material from the mesh
  35245. */
  35246. Material.prototype.unbind = function () {
  35247. this.onUnBindObservable.notifyObservers(this);
  35248. if (this.disableDepthWrite) {
  35249. var engine = this._scene.getEngine();
  35250. engine.setDepthWrite(this._cachedDepthWriteState);
  35251. }
  35252. };
  35253. /**
  35254. * Gets the active textures from the material
  35255. * @returns an array of textures
  35256. */
  35257. Material.prototype.getActiveTextures = function () {
  35258. return [];
  35259. };
  35260. /**
  35261. * Specifies if the material uses a texture
  35262. * @param texture defines the texture to check against the material
  35263. * @returns a boolean specifying if the material uses the texture
  35264. */
  35265. Material.prototype.hasTexture = function (texture) {
  35266. return false;
  35267. };
  35268. /**
  35269. * Makes a duplicate of the material, and gives it a new name
  35270. * @param name defines the new name for the duplicated material
  35271. * @returns the cloned material
  35272. */
  35273. Material.prototype.clone = function (name) {
  35274. return null;
  35275. };
  35276. /**
  35277. * Gets the meshes bound to the material
  35278. * @returns an array of meshes bound to the material
  35279. */
  35280. Material.prototype.getBindedMeshes = function () {
  35281. var result = new Array();
  35282. for (var index = 0; index < this._scene.meshes.length; index++) {
  35283. var mesh = this._scene.meshes[index];
  35284. if (mesh.material === this) {
  35285. result.push(mesh);
  35286. }
  35287. }
  35288. return result;
  35289. };
  35290. /**
  35291. * Force shader compilation
  35292. * @param mesh defines the mesh associated with this material
  35293. * @param onCompiled defines a function to execute once the material is compiled
  35294. * @param options defines the options to configure the compilation
  35295. */
  35296. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35297. var _this = this;
  35298. var localOptions = __assign({ clipPlane: false }, options);
  35299. var subMesh = new BABYLON.BaseSubMesh();
  35300. var scene = this.getScene();
  35301. var checkReady = function () {
  35302. if (!_this._scene || !_this._scene.getEngine()) {
  35303. return;
  35304. }
  35305. if (subMesh._materialDefines) {
  35306. subMesh._materialDefines._renderId = -1;
  35307. }
  35308. var clipPlaneState = scene.clipPlane;
  35309. if (localOptions.clipPlane) {
  35310. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35311. }
  35312. if (_this.storeEffectOnSubMeshes) {
  35313. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35314. if (onCompiled) {
  35315. onCompiled(_this);
  35316. }
  35317. }
  35318. else {
  35319. setTimeout(checkReady, 16);
  35320. }
  35321. }
  35322. else {
  35323. if (_this.isReady(mesh)) {
  35324. if (onCompiled) {
  35325. onCompiled(_this);
  35326. }
  35327. }
  35328. else {
  35329. setTimeout(checkReady, 16);
  35330. }
  35331. }
  35332. if (localOptions.clipPlane) {
  35333. scene.clipPlane = clipPlaneState;
  35334. }
  35335. };
  35336. checkReady();
  35337. };
  35338. /**
  35339. * Force shader compilation
  35340. * @param mesh defines the mesh that will use this material
  35341. * @param options defines additional options for compiling the shaders
  35342. * @returns a promise that resolves when the compilation completes
  35343. */
  35344. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35345. var _this = this;
  35346. return new Promise(function (resolve) {
  35347. _this.forceCompilation(mesh, function () {
  35348. resolve();
  35349. }, options);
  35350. });
  35351. };
  35352. /**
  35353. * Marks a define in the material to indicate that it needs to be re-computed
  35354. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35355. */
  35356. Material.prototype.markAsDirty = function (flag) {
  35357. if (flag & Material.TextureDirtyFlag) {
  35358. this._markAllSubMeshesAsTexturesDirty();
  35359. }
  35360. if (flag & Material.LightDirtyFlag) {
  35361. this._markAllSubMeshesAsLightsDirty();
  35362. }
  35363. if (flag & Material.FresnelDirtyFlag) {
  35364. this._markAllSubMeshesAsFresnelDirty();
  35365. }
  35366. if (flag & Material.AttributesDirtyFlag) {
  35367. this._markAllSubMeshesAsAttributesDirty();
  35368. }
  35369. if (flag & Material.MiscDirtyFlag) {
  35370. this._markAllSubMeshesAsMiscDirty();
  35371. }
  35372. this.getScene().resetCachedMaterial();
  35373. };
  35374. /**
  35375. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35376. * @param func defines a function which checks material defines against the submeshes
  35377. */
  35378. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35379. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35380. var mesh = _a[_i];
  35381. if (!mesh.subMeshes) {
  35382. continue;
  35383. }
  35384. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35385. var subMesh = _c[_b];
  35386. if (subMesh.getMaterial() !== this) {
  35387. continue;
  35388. }
  35389. if (!subMesh._materialDefines) {
  35390. continue;
  35391. }
  35392. func(subMesh._materialDefines);
  35393. }
  35394. }
  35395. };
  35396. /**
  35397. * Indicates that image processing needs to be re-calculated for all submeshes
  35398. */
  35399. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35400. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35401. };
  35402. /**
  35403. * Indicates that textures need to be re-calculated for all submeshes
  35404. */
  35405. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35406. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35407. };
  35408. /**
  35409. * Indicates that fresnel needs to be re-calculated for all submeshes
  35410. */
  35411. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35412. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35413. };
  35414. /**
  35415. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35416. */
  35417. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35418. this._markAllSubMeshesAsDirty(function (defines) {
  35419. defines.markAsFresnelDirty();
  35420. defines.markAsMiscDirty();
  35421. });
  35422. };
  35423. /**
  35424. * Indicates that lights need to be re-calculated for all submeshes
  35425. */
  35426. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35427. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35428. };
  35429. /**
  35430. * Indicates that attributes need to be re-calculated for all submeshes
  35431. */
  35432. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35433. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35434. };
  35435. /**
  35436. * Indicates that misc needs to be re-calculated for all submeshes
  35437. */
  35438. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35439. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35440. };
  35441. /**
  35442. * Indicates that textures and misc need to be re-calculated for all submeshes
  35443. */
  35444. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35445. this._markAllSubMeshesAsDirty(function (defines) {
  35446. defines.markAsTexturesDirty();
  35447. defines.markAsMiscDirty();
  35448. });
  35449. };
  35450. /**
  35451. * Disposes the material
  35452. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35453. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35454. */
  35455. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35456. // Animations
  35457. this.getScene().stopAnimation(this);
  35458. this.getScene().freeProcessedMaterials();
  35459. // Remove from scene
  35460. var index = this._scene.materials.indexOf(this);
  35461. if (index >= 0) {
  35462. this._scene.materials.splice(index, 1);
  35463. }
  35464. // Remove from meshes
  35465. for (index = 0; index < this._scene.meshes.length; index++) {
  35466. var mesh = this._scene.meshes[index];
  35467. if (mesh.material === this) {
  35468. mesh.material = null;
  35469. if (mesh.geometry) {
  35470. var geometry = (mesh.geometry);
  35471. if (this.storeEffectOnSubMeshes) {
  35472. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35473. var subMesh = _a[_i];
  35474. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35475. if (forceDisposeEffect && subMesh._materialEffect) {
  35476. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35477. }
  35478. }
  35479. }
  35480. else {
  35481. geometry._releaseVertexArrayObject(this._effect);
  35482. }
  35483. }
  35484. }
  35485. }
  35486. this._uniformBuffer.dispose();
  35487. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35488. if (forceDisposeEffect && this._effect) {
  35489. if (!this.storeEffectOnSubMeshes) {
  35490. this._scene.getEngine()._releaseEffect(this._effect);
  35491. }
  35492. this._effect = null;
  35493. }
  35494. // Callback
  35495. this.onDisposeObservable.notifyObservers(this);
  35496. this.onDisposeObservable.clear();
  35497. this.onBindObservable.clear();
  35498. this.onUnBindObservable.clear();
  35499. };
  35500. /**
  35501. * Serializes this material
  35502. * @returns the serialized material object
  35503. */
  35504. Material.prototype.serialize = function () {
  35505. return BABYLON.SerializationHelper.Serialize(this);
  35506. };
  35507. /**
  35508. * Creates a MultiMaterial from parsed MultiMaterial data.
  35509. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35510. * @param scene defines the hosting scene
  35511. * @returns a new MultiMaterial
  35512. */
  35513. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35514. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35515. multiMaterial.id = parsedMultiMaterial.id;
  35516. if (BABYLON.Tags) {
  35517. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35518. }
  35519. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35520. var subMatId = parsedMultiMaterial.materials[matIndex];
  35521. if (subMatId) {
  35522. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35523. }
  35524. else {
  35525. multiMaterial.subMaterials.push(null);
  35526. }
  35527. }
  35528. return multiMaterial;
  35529. };
  35530. /**
  35531. * Creates a material from parsed material data
  35532. * @param parsedMaterial defines parsed material data
  35533. * @param scene defines the hosting scene
  35534. * @param rootUrl defines the root URL to use to load textures
  35535. * @returns a new material
  35536. */
  35537. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35538. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35539. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35540. }
  35541. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35542. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35543. if (!BABYLON.LegacyPBRMaterial) {
  35544. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35545. return;
  35546. }
  35547. }
  35548. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35549. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35550. };
  35551. // Triangle views
  35552. Material._TriangleFillMode = 0;
  35553. Material._WireFrameFillMode = 1;
  35554. Material._PointFillMode = 2;
  35555. // Draw modes
  35556. Material._PointListDrawMode = 3;
  35557. Material._LineListDrawMode = 4;
  35558. Material._LineLoopDrawMode = 5;
  35559. Material._LineStripDrawMode = 6;
  35560. Material._TriangleStripDrawMode = 7;
  35561. Material._TriangleFanDrawMode = 8;
  35562. /**
  35563. * Stores the clock-wise side orientation
  35564. */
  35565. Material._ClockWiseSideOrientation = 0;
  35566. /**
  35567. * Stores the counter clock-wise side orientation
  35568. */
  35569. Material._CounterClockWiseSideOrientation = 1;
  35570. /**
  35571. * The dirty texture flag value
  35572. */
  35573. Material._TextureDirtyFlag = 1;
  35574. /**
  35575. * The dirty light flag value
  35576. */
  35577. Material._LightDirtyFlag = 2;
  35578. /**
  35579. * The dirty fresnel flag value
  35580. */
  35581. Material._FresnelDirtyFlag = 4;
  35582. /**
  35583. * The dirty attribute flag value
  35584. */
  35585. Material._AttributesDirtyFlag = 8;
  35586. /**
  35587. * The dirty misc flag value
  35588. */
  35589. Material._MiscDirtyFlag = 16;
  35590. __decorate([
  35591. BABYLON.serialize()
  35592. ], Material.prototype, "id", void 0);
  35593. __decorate([
  35594. BABYLON.serialize()
  35595. ], Material.prototype, "name", void 0);
  35596. __decorate([
  35597. BABYLON.serialize()
  35598. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35599. __decorate([
  35600. BABYLON.serialize()
  35601. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35602. __decorate([
  35603. BABYLON.serialize()
  35604. ], Material.prototype, "state", void 0);
  35605. __decorate([
  35606. BABYLON.serialize("alpha")
  35607. ], Material.prototype, "_alpha", void 0);
  35608. __decorate([
  35609. BABYLON.serialize("backFaceCulling")
  35610. ], Material.prototype, "_backFaceCulling", void 0);
  35611. __decorate([
  35612. BABYLON.serialize()
  35613. ], Material.prototype, "sideOrientation", void 0);
  35614. __decorate([
  35615. BABYLON.serialize("alphaMode")
  35616. ], Material.prototype, "_alphaMode", void 0);
  35617. __decorate([
  35618. BABYLON.serialize()
  35619. ], Material.prototype, "_needDepthPrePass", void 0);
  35620. __decorate([
  35621. BABYLON.serialize()
  35622. ], Material.prototype, "disableDepthWrite", void 0);
  35623. __decorate([
  35624. BABYLON.serialize()
  35625. ], Material.prototype, "forceDepthWrite", void 0);
  35626. __decorate([
  35627. BABYLON.serialize()
  35628. ], Material.prototype, "separateCullingPass", void 0);
  35629. __decorate([
  35630. BABYLON.serialize("fogEnabled")
  35631. ], Material.prototype, "_fogEnabled", void 0);
  35632. __decorate([
  35633. BABYLON.serialize()
  35634. ], Material.prototype, "pointSize", void 0);
  35635. __decorate([
  35636. BABYLON.serialize()
  35637. ], Material.prototype, "zOffset", void 0);
  35638. __decorate([
  35639. BABYLON.serialize()
  35640. ], Material.prototype, "wireframe", null);
  35641. __decorate([
  35642. BABYLON.serialize()
  35643. ], Material.prototype, "pointsCloud", null);
  35644. __decorate([
  35645. BABYLON.serialize()
  35646. ], Material.prototype, "fillMode", null);
  35647. return Material;
  35648. }());
  35649. BABYLON.Material = Material;
  35650. })(BABYLON || (BABYLON = {}));
  35651. //# sourceMappingURL=babylon.material.js.map
  35652. var BABYLON;
  35653. (function (BABYLON) {
  35654. var UniformBuffer = /** @class */ (function () {
  35655. /**
  35656. * Uniform buffer objects.
  35657. *
  35658. * Handles blocks of uniform on the GPU.
  35659. *
  35660. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35661. *
  35662. * For more information, please refer to :
  35663. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35664. */
  35665. function UniformBuffer(engine, data, dynamic) {
  35666. this._engine = engine;
  35667. this._noUBO = !engine.supportsUniformBuffers;
  35668. this._dynamic = dynamic;
  35669. this._data = data || [];
  35670. this._uniformLocations = {};
  35671. this._uniformSizes = {};
  35672. this._uniformLocationPointer = 0;
  35673. this._needSync = false;
  35674. if (this._noUBO) {
  35675. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35676. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35677. this.updateFloat = this._updateFloatForEffect;
  35678. this.updateFloat2 = this._updateFloat2ForEffect;
  35679. this.updateFloat3 = this._updateFloat3ForEffect;
  35680. this.updateFloat4 = this._updateFloat4ForEffect;
  35681. this.updateMatrix = this._updateMatrixForEffect;
  35682. this.updateVector3 = this._updateVector3ForEffect;
  35683. this.updateVector4 = this._updateVector4ForEffect;
  35684. this.updateColor3 = this._updateColor3ForEffect;
  35685. this.updateColor4 = this._updateColor4ForEffect;
  35686. }
  35687. else {
  35688. this._engine._uniformBuffers.push(this);
  35689. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35690. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35691. this.updateFloat = this._updateFloatForUniform;
  35692. this.updateFloat2 = this._updateFloat2ForUniform;
  35693. this.updateFloat3 = this._updateFloat3ForUniform;
  35694. this.updateFloat4 = this._updateFloat4ForUniform;
  35695. this.updateMatrix = this._updateMatrixForUniform;
  35696. this.updateVector3 = this._updateVector3ForUniform;
  35697. this.updateVector4 = this._updateVector4ForUniform;
  35698. this.updateColor3 = this._updateColor3ForUniform;
  35699. this.updateColor4 = this._updateColor4ForUniform;
  35700. }
  35701. }
  35702. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35703. // Properties
  35704. /**
  35705. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35706. * or just falling back on setUniformXXX calls.
  35707. */
  35708. get: function () {
  35709. return !this._noUBO;
  35710. },
  35711. enumerable: true,
  35712. configurable: true
  35713. });
  35714. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35715. /**
  35716. * Indicates if the WebGL underlying uniform buffer is in sync
  35717. * with the javascript cache data.
  35718. */
  35719. get: function () {
  35720. return !this._needSync;
  35721. },
  35722. enumerable: true,
  35723. configurable: true
  35724. });
  35725. /**
  35726. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35727. * Also, a dynamic UniformBuffer will disable cache verification and always
  35728. * update the underlying WebGL uniform buffer to the GPU.
  35729. */
  35730. UniformBuffer.prototype.isDynamic = function () {
  35731. return this._dynamic !== undefined;
  35732. };
  35733. /**
  35734. * The data cache on JS side.
  35735. */
  35736. UniformBuffer.prototype.getData = function () {
  35737. return this._bufferData;
  35738. };
  35739. /**
  35740. * The underlying WebGL Uniform buffer.
  35741. */
  35742. UniformBuffer.prototype.getBuffer = function () {
  35743. return this._buffer;
  35744. };
  35745. /**
  35746. * std140 layout specifies how to align data within an UBO structure.
  35747. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35748. * for specs.
  35749. */
  35750. UniformBuffer.prototype._fillAlignment = function (size) {
  35751. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35752. // and 4x4 matrices
  35753. // TODO : change if other types are used
  35754. var alignment;
  35755. if (size <= 2) {
  35756. alignment = size;
  35757. }
  35758. else {
  35759. alignment = 4;
  35760. }
  35761. if ((this._uniformLocationPointer % alignment) !== 0) {
  35762. var oldPointer = this._uniformLocationPointer;
  35763. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35764. var diff = this._uniformLocationPointer - oldPointer;
  35765. for (var i = 0; i < diff; i++) {
  35766. this._data.push(0);
  35767. }
  35768. }
  35769. };
  35770. /**
  35771. * Adds an uniform in the buffer.
  35772. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35773. * for the layout to be correct !
  35774. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35775. * @param {number|number[]} size Data size, or data directly.
  35776. */
  35777. UniformBuffer.prototype.addUniform = function (name, size) {
  35778. if (this._noUBO) {
  35779. return;
  35780. }
  35781. if (this._uniformLocations[name] !== undefined) {
  35782. // Already existing uniform
  35783. return;
  35784. }
  35785. // This function must be called in the order of the shader layout !
  35786. // size can be the size of the uniform, or data directly
  35787. var data;
  35788. if (size instanceof Array) {
  35789. data = size;
  35790. size = data.length;
  35791. }
  35792. else {
  35793. size = size;
  35794. data = [];
  35795. // Fill with zeros
  35796. for (var i = 0; i < size; i++) {
  35797. data.push(0);
  35798. }
  35799. }
  35800. this._fillAlignment(size);
  35801. this._uniformSizes[name] = size;
  35802. this._uniformLocations[name] = this._uniformLocationPointer;
  35803. this._uniformLocationPointer += size;
  35804. for (var i = 0; i < size; i++) {
  35805. this._data.push(data[i]);
  35806. }
  35807. this._needSync = true;
  35808. };
  35809. /**
  35810. * Wrapper for addUniform.
  35811. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35812. * @param {Matrix} mat A 4x4 matrix.
  35813. */
  35814. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35815. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35816. };
  35817. /**
  35818. * Wrapper for addUniform.
  35819. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35820. * @param {number} x
  35821. * @param {number} y
  35822. */
  35823. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35824. var temp = [x, y];
  35825. this.addUniform(name, temp);
  35826. };
  35827. /**
  35828. * Wrapper for addUniform.
  35829. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35830. * @param {number} x
  35831. * @param {number} y
  35832. * @param {number} z
  35833. */
  35834. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35835. var temp = [x, y, z];
  35836. this.addUniform(name, temp);
  35837. };
  35838. /**
  35839. * Wrapper for addUniform.
  35840. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35841. * @param {Color3} color
  35842. */
  35843. UniformBuffer.prototype.addColor3 = function (name, color) {
  35844. var temp = new Array();
  35845. color.toArray(temp);
  35846. this.addUniform(name, temp);
  35847. };
  35848. /**
  35849. * Wrapper for addUniform.
  35850. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35851. * @param {Color3} color
  35852. * @param {number} alpha
  35853. */
  35854. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35855. var temp = new Array();
  35856. color.toArray(temp);
  35857. temp.push(alpha);
  35858. this.addUniform(name, temp);
  35859. };
  35860. /**
  35861. * Wrapper for addUniform.
  35862. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35863. * @param {Vector3} vector
  35864. */
  35865. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35866. var temp = new Array();
  35867. vector.toArray(temp);
  35868. this.addUniform(name, temp);
  35869. };
  35870. /**
  35871. * Wrapper for addUniform.
  35872. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35873. */
  35874. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35875. this.addUniform(name, 12);
  35876. };
  35877. /**
  35878. * Wrapper for addUniform.
  35879. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35880. */
  35881. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35882. this.addUniform(name, 8);
  35883. };
  35884. /**
  35885. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35886. */
  35887. UniformBuffer.prototype.create = function () {
  35888. if (this._noUBO) {
  35889. return;
  35890. }
  35891. if (this._buffer) {
  35892. return; // nothing to do
  35893. }
  35894. // See spec, alignment must be filled as a vec4
  35895. this._fillAlignment(4);
  35896. this._bufferData = new Float32Array(this._data);
  35897. this._rebuild();
  35898. this._needSync = true;
  35899. };
  35900. UniformBuffer.prototype._rebuild = function () {
  35901. if (this._noUBO) {
  35902. return;
  35903. }
  35904. if (this._dynamic) {
  35905. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35906. }
  35907. else {
  35908. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35909. }
  35910. };
  35911. /**
  35912. * Updates the WebGL Uniform Buffer on the GPU.
  35913. * If the `dynamic` flag is set to true, no cache comparison is done.
  35914. * Otherwise, the buffer will be updated only if the cache differs.
  35915. */
  35916. UniformBuffer.prototype.update = function () {
  35917. if (!this._buffer) {
  35918. this.create();
  35919. return;
  35920. }
  35921. if (!this._dynamic && !this._needSync) {
  35922. return;
  35923. }
  35924. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35925. this._needSync = false;
  35926. };
  35927. /**
  35928. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35929. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35930. * @param {number[]|Float32Array} data Flattened data
  35931. * @param {number} size Size of the data.
  35932. */
  35933. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35934. var location = this._uniformLocations[uniformName];
  35935. if (location === undefined) {
  35936. if (this._buffer) {
  35937. // Cannot add an uniform if the buffer is already created
  35938. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35939. return;
  35940. }
  35941. this.addUniform(uniformName, size);
  35942. location = this._uniformLocations[uniformName];
  35943. }
  35944. if (!this._buffer) {
  35945. this.create();
  35946. }
  35947. if (!this._dynamic) {
  35948. // Cache for static uniform buffers
  35949. var changed = false;
  35950. for (var i = 0; i < size; i++) {
  35951. if (this._bufferData[location + i] !== data[i]) {
  35952. changed = true;
  35953. this._bufferData[location + i] = data[i];
  35954. }
  35955. }
  35956. this._needSync = this._needSync || changed;
  35957. }
  35958. else {
  35959. // No cache for dynamic
  35960. for (var i = 0; i < size; i++) {
  35961. this._bufferData[location + i] = data[i];
  35962. }
  35963. }
  35964. };
  35965. // Update methods
  35966. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35967. // To match std140, matrix must be realigned
  35968. for (var i = 0; i < 3; i++) {
  35969. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35970. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35971. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35972. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35973. }
  35974. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35975. };
  35976. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35977. this._currentEffect.setMatrix3x3(name, matrix);
  35978. };
  35979. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35980. this._currentEffect.setMatrix2x2(name, matrix);
  35981. };
  35982. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35983. // To match std140, matrix must be realigned
  35984. for (var i = 0; i < 2; i++) {
  35985. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35986. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35987. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35988. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35989. }
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35991. };
  35992. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35993. this._currentEffect.setFloat(name, x);
  35994. };
  35995. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35996. UniformBuffer._tempBuffer[0] = x;
  35997. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35998. };
  35999. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36000. if (suffix === void 0) { suffix = ""; }
  36001. this._currentEffect.setFloat2(name + suffix, x, y);
  36002. };
  36003. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36004. if (suffix === void 0) { suffix = ""; }
  36005. UniformBuffer._tempBuffer[0] = x;
  36006. UniformBuffer._tempBuffer[1] = y;
  36007. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36008. };
  36009. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36010. if (suffix === void 0) { suffix = ""; }
  36011. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36012. };
  36013. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36014. if (suffix === void 0) { suffix = ""; }
  36015. UniformBuffer._tempBuffer[0] = x;
  36016. UniformBuffer._tempBuffer[1] = y;
  36017. UniformBuffer._tempBuffer[2] = z;
  36018. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36019. };
  36020. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36021. if (suffix === void 0) { suffix = ""; }
  36022. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36023. };
  36024. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36025. if (suffix === void 0) { suffix = ""; }
  36026. UniformBuffer._tempBuffer[0] = x;
  36027. UniformBuffer._tempBuffer[1] = y;
  36028. UniformBuffer._tempBuffer[2] = z;
  36029. UniformBuffer._tempBuffer[3] = w;
  36030. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36031. };
  36032. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36033. this._currentEffect.setMatrix(name, mat);
  36034. };
  36035. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36036. this.updateUniform(name, mat.toArray(), 16);
  36037. };
  36038. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36039. this._currentEffect.setVector3(name, vector);
  36040. };
  36041. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36042. vector.toArray(UniformBuffer._tempBuffer);
  36043. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36044. };
  36045. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36046. this._currentEffect.setVector4(name, vector);
  36047. };
  36048. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36049. vector.toArray(UniformBuffer._tempBuffer);
  36050. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36051. };
  36052. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36053. if (suffix === void 0) { suffix = ""; }
  36054. this._currentEffect.setColor3(name + suffix, color);
  36055. };
  36056. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36057. if (suffix === void 0) { suffix = ""; }
  36058. color.toArray(UniformBuffer._tempBuffer);
  36059. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36060. };
  36061. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36062. if (suffix === void 0) { suffix = ""; }
  36063. this._currentEffect.setColor4(name + suffix, color, alpha);
  36064. };
  36065. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36066. if (suffix === void 0) { suffix = ""; }
  36067. color.toArray(UniformBuffer._tempBuffer);
  36068. UniformBuffer._tempBuffer[3] = alpha;
  36069. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36070. };
  36071. /**
  36072. * Sets a sampler uniform on the effect.
  36073. * @param {string} name Name of the sampler.
  36074. * @param {Texture} texture
  36075. */
  36076. UniformBuffer.prototype.setTexture = function (name, texture) {
  36077. this._currentEffect.setTexture(name, texture);
  36078. };
  36079. /**
  36080. * Directly updates the value of the uniform in the cache AND on the GPU.
  36081. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36082. * @param {number[]|Float32Array} data Flattened data
  36083. */
  36084. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36085. this.updateUniform(uniformName, data, data.length);
  36086. this.update();
  36087. };
  36088. /**
  36089. * Binds this uniform buffer to an effect.
  36090. * @param {Effect} effect
  36091. * @param {string} name Name of the uniform block in the shader.
  36092. */
  36093. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36094. this._currentEffect = effect;
  36095. if (this._noUBO || !this._buffer) {
  36096. return;
  36097. }
  36098. effect.bindUniformBuffer(this._buffer, name);
  36099. };
  36100. /**
  36101. * Disposes the uniform buffer.
  36102. */
  36103. UniformBuffer.prototype.dispose = function () {
  36104. if (this._noUBO) {
  36105. return;
  36106. }
  36107. var index = this._engine._uniformBuffers.indexOf(this);
  36108. if (index !== -1) {
  36109. this._engine._uniformBuffers.splice(index, 1);
  36110. }
  36111. if (!this._buffer) {
  36112. return;
  36113. }
  36114. if (this._engine._releaseBuffer(this._buffer)) {
  36115. this._buffer = null;
  36116. }
  36117. };
  36118. // Pool for avoiding memory leaks
  36119. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36120. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36121. return UniformBuffer;
  36122. }());
  36123. BABYLON.UniformBuffer = UniformBuffer;
  36124. })(BABYLON || (BABYLON = {}));
  36125. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36126. var BABYLON;
  36127. (function (BABYLON) {
  36128. /**
  36129. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36130. */
  36131. var VertexData = /** @class */ (function () {
  36132. function VertexData() {
  36133. }
  36134. /**
  36135. * Uses the passed data array to set the set the values for the specified kind of data
  36136. * @param data a linear array of floating numbers
  36137. * @param kind the type of data that is being set, eg positions, colors etc
  36138. */
  36139. VertexData.prototype.set = function (data, kind) {
  36140. switch (kind) {
  36141. case BABYLON.VertexBuffer.PositionKind:
  36142. this.positions = data;
  36143. break;
  36144. case BABYLON.VertexBuffer.NormalKind:
  36145. this.normals = data;
  36146. break;
  36147. case BABYLON.VertexBuffer.TangentKind:
  36148. this.tangents = data;
  36149. break;
  36150. case BABYLON.VertexBuffer.UVKind:
  36151. this.uvs = data;
  36152. break;
  36153. case BABYLON.VertexBuffer.UV2Kind:
  36154. this.uvs2 = data;
  36155. break;
  36156. case BABYLON.VertexBuffer.UV3Kind:
  36157. this.uvs3 = data;
  36158. break;
  36159. case BABYLON.VertexBuffer.UV4Kind:
  36160. this.uvs4 = data;
  36161. break;
  36162. case BABYLON.VertexBuffer.UV5Kind:
  36163. this.uvs5 = data;
  36164. break;
  36165. case BABYLON.VertexBuffer.UV6Kind:
  36166. this.uvs6 = data;
  36167. break;
  36168. case BABYLON.VertexBuffer.ColorKind:
  36169. this.colors = data;
  36170. break;
  36171. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36172. this.matricesIndices = data;
  36173. break;
  36174. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36175. this.matricesWeights = data;
  36176. break;
  36177. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36178. this.matricesIndicesExtra = data;
  36179. break;
  36180. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36181. this.matricesWeightsExtra = data;
  36182. break;
  36183. }
  36184. };
  36185. /**
  36186. * Associates the vertexData to the passed Mesh.
  36187. * Sets it as updatable or not (default `false`)
  36188. * @param mesh the mesh the vertexData is applied to
  36189. * @param updatable when used and having the value true allows new data to update the vertexData
  36190. * @returns the VertexData
  36191. */
  36192. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36193. this._applyTo(mesh, updatable);
  36194. return this;
  36195. };
  36196. /**
  36197. * Associates the vertexData to the passed Geometry.
  36198. * Sets it as updatable or not (default `false`)
  36199. * @param geometry the geometry the vertexData is applied to
  36200. * @param updatable when used and having the value true allows new data to update the vertexData
  36201. * @returns VertexData
  36202. */
  36203. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36204. this._applyTo(geometry, updatable);
  36205. return this;
  36206. };
  36207. /**
  36208. * Updates the associated mesh
  36209. * @param mesh the mesh to be updated
  36210. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36211. * @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
  36212. * @returns VertexData
  36213. */
  36214. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36215. this._update(mesh);
  36216. return this;
  36217. };
  36218. /**
  36219. * Updates the associated geometry
  36220. * @param geometry the geometry to be updated
  36221. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36222. * @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
  36223. * @returns VertexData.
  36224. */
  36225. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36226. this._update(geometry);
  36227. return this;
  36228. };
  36229. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36230. if (updatable === void 0) { updatable = false; }
  36231. if (this.positions) {
  36232. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36233. }
  36234. if (this.normals) {
  36235. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36236. }
  36237. if (this.tangents) {
  36238. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36239. }
  36240. if (this.uvs) {
  36241. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36242. }
  36243. if (this.uvs2) {
  36244. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36245. }
  36246. if (this.uvs3) {
  36247. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36248. }
  36249. if (this.uvs4) {
  36250. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36251. }
  36252. if (this.uvs5) {
  36253. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36254. }
  36255. if (this.uvs6) {
  36256. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36257. }
  36258. if (this.colors) {
  36259. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36260. }
  36261. if (this.matricesIndices) {
  36262. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36263. }
  36264. if (this.matricesWeights) {
  36265. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36266. }
  36267. if (this.matricesIndicesExtra) {
  36268. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36269. }
  36270. if (this.matricesWeightsExtra) {
  36271. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36272. }
  36273. if (this.indices) {
  36274. meshOrGeometry.setIndices(this.indices, null, updatable);
  36275. }
  36276. return this;
  36277. };
  36278. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36279. if (this.positions) {
  36280. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36281. }
  36282. if (this.normals) {
  36283. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36284. }
  36285. if (this.tangents) {
  36286. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36287. }
  36288. if (this.uvs) {
  36289. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36290. }
  36291. if (this.uvs2) {
  36292. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36293. }
  36294. if (this.uvs3) {
  36295. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36296. }
  36297. if (this.uvs4) {
  36298. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36299. }
  36300. if (this.uvs5) {
  36301. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36302. }
  36303. if (this.uvs6) {
  36304. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36305. }
  36306. if (this.colors) {
  36307. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36308. }
  36309. if (this.matricesIndices) {
  36310. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36311. }
  36312. if (this.matricesWeights) {
  36313. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36314. }
  36315. if (this.matricesIndicesExtra) {
  36316. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36317. }
  36318. if (this.matricesWeightsExtra) {
  36319. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36320. }
  36321. if (this.indices) {
  36322. meshOrGeometry.setIndices(this.indices, null);
  36323. }
  36324. return this;
  36325. };
  36326. /**
  36327. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36328. * @param matrix the transforming matrix
  36329. * @returns the VertexData
  36330. */
  36331. VertexData.prototype.transform = function (matrix) {
  36332. var transformed = BABYLON.Vector3.Zero();
  36333. var index;
  36334. if (this.positions) {
  36335. var position = BABYLON.Vector3.Zero();
  36336. for (index = 0; index < this.positions.length; index += 3) {
  36337. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36338. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36339. this.positions[index] = transformed.x;
  36340. this.positions[index + 1] = transformed.y;
  36341. this.positions[index + 2] = transformed.z;
  36342. }
  36343. }
  36344. if (this.normals) {
  36345. var normal = BABYLON.Vector3.Zero();
  36346. for (index = 0; index < this.normals.length; index += 3) {
  36347. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36348. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36349. this.normals[index] = transformed.x;
  36350. this.normals[index + 1] = transformed.y;
  36351. this.normals[index + 2] = transformed.z;
  36352. }
  36353. }
  36354. if (this.tangents) {
  36355. var tangent = BABYLON.Vector4.Zero();
  36356. var tangentTransformed = BABYLON.Vector4.Zero();
  36357. for (index = 0; index < this.tangents.length; index += 4) {
  36358. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36359. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36360. this.tangents[index] = tangentTransformed.x;
  36361. this.tangents[index + 1] = tangentTransformed.y;
  36362. this.tangents[index + 2] = tangentTransformed.z;
  36363. this.tangents[index + 3] = tangentTransformed.w;
  36364. }
  36365. }
  36366. return this;
  36367. };
  36368. /**
  36369. * Merges the passed VertexData into the current one
  36370. * @param other the VertexData to be merged into the current one
  36371. * @returns the modified VertexData
  36372. */
  36373. VertexData.prototype.merge = function (other) {
  36374. this._validate();
  36375. other._validate();
  36376. if (!this.normals !== !other.normals ||
  36377. !this.tangents !== !other.tangents ||
  36378. !this.uvs !== !other.uvs ||
  36379. !this.uvs2 !== !other.uvs2 ||
  36380. !this.uvs3 !== !other.uvs3 ||
  36381. !this.uvs4 !== !other.uvs4 ||
  36382. !this.uvs5 !== !other.uvs5 ||
  36383. !this.uvs6 !== !other.uvs6 ||
  36384. !this.colors !== !other.colors ||
  36385. !this.matricesIndices !== !other.matricesIndices ||
  36386. !this.matricesWeights !== !other.matricesWeights ||
  36387. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36388. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36389. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36390. }
  36391. if (other.indices) {
  36392. if (!this.indices) {
  36393. this.indices = [];
  36394. }
  36395. var offset = this.positions ? this.positions.length / 3 : 0;
  36396. for (var index = 0; index < other.indices.length; index++) {
  36397. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36398. this.indices.push(other.indices[index] + offset);
  36399. }
  36400. }
  36401. this.positions = this._mergeElement(this.positions, other.positions);
  36402. this.normals = this._mergeElement(this.normals, other.normals);
  36403. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36404. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36405. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36406. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36407. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36408. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36409. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36410. this.colors = this._mergeElement(this.colors, other.colors);
  36411. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36412. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36413. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36414. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36415. return this;
  36416. };
  36417. VertexData.prototype._mergeElement = function (source, other) {
  36418. if (!source) {
  36419. return other;
  36420. }
  36421. if (!other) {
  36422. return source;
  36423. }
  36424. var len = other.length + source.length;
  36425. var isSrcTypedArray = source instanceof Float32Array;
  36426. var isOthTypedArray = other instanceof Float32Array;
  36427. // use non-loop method when the source is Float32Array
  36428. if (isSrcTypedArray) {
  36429. var ret32 = new Float32Array(len);
  36430. ret32.set(source);
  36431. ret32.set(other, source.length);
  36432. return ret32;
  36433. // source is number[], when other is also use concat
  36434. }
  36435. else if (!isOthTypedArray) {
  36436. return source.concat(other);
  36437. // source is a number[], but other is a Float32Array, loop required
  36438. }
  36439. else {
  36440. var ret = source.slice(0); // copy source to a separate array
  36441. for (var i = 0, len = other.length; i < len; i++) {
  36442. ret.push(other[i]);
  36443. }
  36444. return ret;
  36445. }
  36446. };
  36447. VertexData.prototype._validate = function () {
  36448. if (!this.positions) {
  36449. throw new Error("Positions are required");
  36450. }
  36451. var getElementCount = function (kind, values) {
  36452. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36453. if ((values.length % stride) !== 0) {
  36454. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36455. }
  36456. return values.length / stride;
  36457. };
  36458. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36459. var validateElementCount = function (kind, values) {
  36460. var elementCount = getElementCount(kind, values);
  36461. if (elementCount !== positionsElementCount) {
  36462. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36463. }
  36464. };
  36465. if (this.normals)
  36466. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36467. if (this.tangents)
  36468. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36469. if (this.uvs)
  36470. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36471. if (this.uvs2)
  36472. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36473. if (this.uvs3)
  36474. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36475. if (this.uvs4)
  36476. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36477. if (this.uvs5)
  36478. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36479. if (this.uvs6)
  36480. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36481. if (this.colors)
  36482. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36483. if (this.matricesIndices)
  36484. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36485. if (this.matricesWeights)
  36486. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36487. if (this.matricesIndicesExtra)
  36488. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36489. if (this.matricesWeightsExtra)
  36490. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36491. };
  36492. /**
  36493. * Serializes the VertexData
  36494. * @returns a serialized object
  36495. */
  36496. VertexData.prototype.serialize = function () {
  36497. var serializationObject = this.serialize();
  36498. if (this.positions) {
  36499. serializationObject.positions = this.positions;
  36500. }
  36501. if (this.normals) {
  36502. serializationObject.normals = this.normals;
  36503. }
  36504. if (this.tangents) {
  36505. serializationObject.tangents = this.tangents;
  36506. }
  36507. if (this.uvs) {
  36508. serializationObject.uvs = this.uvs;
  36509. }
  36510. if (this.uvs2) {
  36511. serializationObject.uvs2 = this.uvs2;
  36512. }
  36513. if (this.uvs3) {
  36514. serializationObject.uvs3 = this.uvs3;
  36515. }
  36516. if (this.uvs4) {
  36517. serializationObject.uvs4 = this.uvs4;
  36518. }
  36519. if (this.uvs5) {
  36520. serializationObject.uvs5 = this.uvs5;
  36521. }
  36522. if (this.uvs6) {
  36523. serializationObject.uvs6 = this.uvs6;
  36524. }
  36525. if (this.colors) {
  36526. serializationObject.colors = this.colors;
  36527. }
  36528. if (this.matricesIndices) {
  36529. serializationObject.matricesIndices = this.matricesIndices;
  36530. serializationObject.matricesIndices._isExpanded = true;
  36531. }
  36532. if (this.matricesWeights) {
  36533. serializationObject.matricesWeights = this.matricesWeights;
  36534. }
  36535. if (this.matricesIndicesExtra) {
  36536. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36537. serializationObject.matricesIndicesExtra._isExpanded = true;
  36538. }
  36539. if (this.matricesWeightsExtra) {
  36540. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36541. }
  36542. serializationObject.indices = this.indices;
  36543. return serializationObject;
  36544. };
  36545. // Statics
  36546. /**
  36547. * Extracts the vertexData from a mesh
  36548. * @param mesh the mesh from which to extract the VertexData
  36549. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36550. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36551. * @returns the object VertexData associated to the passed mesh
  36552. */
  36553. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36554. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36555. };
  36556. /**
  36557. * Extracts the vertexData from the geometry
  36558. * @param geometry the geometry from which to extract the VertexData
  36559. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36560. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36561. * @returns the object VertexData associated to the passed mesh
  36562. */
  36563. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36564. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36565. };
  36566. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36567. var result = new VertexData();
  36568. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36569. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36570. }
  36571. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36572. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36573. }
  36574. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36575. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36576. }
  36577. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36578. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36579. }
  36580. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36581. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36582. }
  36583. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36584. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36585. }
  36586. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36587. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36588. }
  36589. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36590. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36591. }
  36592. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36593. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36594. }
  36595. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36596. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36597. }
  36598. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36599. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36600. }
  36601. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36602. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36603. }
  36604. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36605. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36606. }
  36607. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36608. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36609. }
  36610. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36611. return result;
  36612. };
  36613. /**
  36614. * Creates the VertexData for a Ribbon
  36615. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36616. * * pathArray array of paths, each of which an array of successive Vector3
  36617. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36618. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36619. * * 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
  36620. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36621. * * 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)
  36622. * * 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)
  36623. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36624. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36625. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36626. * @returns the VertexData of the ribbon
  36627. */
  36628. VertexData.CreateRibbon = function (options) {
  36629. var pathArray = options.pathArray;
  36630. var closeArray = options.closeArray || false;
  36631. var closePath = options.closePath || false;
  36632. var invertUV = options.invertUV || false;
  36633. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36634. var offset = options.offset || defaultOffset;
  36635. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36636. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36637. var customUV = options.uvs;
  36638. var customColors = options.colors;
  36639. var positions = [];
  36640. var indices = [];
  36641. var normals = [];
  36642. var uvs = [];
  36643. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36644. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36645. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36646. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36647. var minlg; // minimal length among all paths from pathArray
  36648. var lg = []; // array of path lengths : nb of vertex per path
  36649. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36650. var p; // path iterator
  36651. var i; // point iterator
  36652. var j; // point iterator
  36653. // if single path in pathArray
  36654. if (pathArray.length < 2) {
  36655. var ar1 = [];
  36656. var ar2 = [];
  36657. for (i = 0; i < pathArray[0].length - offset; i++) {
  36658. ar1.push(pathArray[0][i]);
  36659. ar2.push(pathArray[0][i + offset]);
  36660. }
  36661. pathArray = [ar1, ar2];
  36662. }
  36663. // positions and horizontal distances (u)
  36664. var idc = 0;
  36665. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36666. var path;
  36667. var l;
  36668. minlg = pathArray[0].length;
  36669. var vectlg;
  36670. var dist;
  36671. for (p = 0; p < pathArray.length; p++) {
  36672. uTotalDistance[p] = 0;
  36673. us[p] = [0];
  36674. path = pathArray[p];
  36675. l = path.length;
  36676. minlg = (minlg < l) ? minlg : l;
  36677. j = 0;
  36678. while (j < l) {
  36679. positions.push(path[j].x, path[j].y, path[j].z);
  36680. if (j > 0) {
  36681. vectlg = path[j].subtract(path[j - 1]).length();
  36682. dist = vectlg + uTotalDistance[p];
  36683. us[p].push(dist);
  36684. uTotalDistance[p] = dist;
  36685. }
  36686. j++;
  36687. }
  36688. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36689. j--;
  36690. positions.push(path[0].x, path[0].y, path[0].z);
  36691. vectlg = path[j].subtract(path[0]).length();
  36692. dist = vectlg + uTotalDistance[p];
  36693. us[p].push(dist);
  36694. uTotalDistance[p] = dist;
  36695. }
  36696. lg[p] = l + closePathCorr;
  36697. idx[p] = idc;
  36698. idc += (l + closePathCorr);
  36699. }
  36700. // vertical distances (v)
  36701. var path1;
  36702. var path2;
  36703. var vertex1 = null;
  36704. var vertex2 = null;
  36705. for (i = 0; i < minlg + closePathCorr; i++) {
  36706. vTotalDistance[i] = 0;
  36707. vs[i] = [0];
  36708. for (p = 0; p < pathArray.length - 1; p++) {
  36709. path1 = pathArray[p];
  36710. path2 = pathArray[p + 1];
  36711. if (i === minlg) { // closePath
  36712. vertex1 = path1[0];
  36713. vertex2 = path2[0];
  36714. }
  36715. else {
  36716. vertex1 = path1[i];
  36717. vertex2 = path2[i];
  36718. }
  36719. vectlg = vertex2.subtract(vertex1).length();
  36720. dist = vectlg + vTotalDistance[i];
  36721. vs[i].push(dist);
  36722. vTotalDistance[i] = dist;
  36723. }
  36724. if (closeArray && vertex2 && vertex1) {
  36725. path1 = pathArray[p];
  36726. path2 = pathArray[0];
  36727. if (i === minlg) { // closePath
  36728. vertex2 = path2[0];
  36729. }
  36730. vectlg = vertex2.subtract(vertex1).length();
  36731. dist = vectlg + vTotalDistance[i];
  36732. vTotalDistance[i] = dist;
  36733. }
  36734. }
  36735. // uvs
  36736. var u;
  36737. var v;
  36738. if (customUV) {
  36739. for (p = 0; p < customUV.length; p++) {
  36740. uvs.push(customUV[p].x, customUV[p].y);
  36741. }
  36742. }
  36743. else {
  36744. for (p = 0; p < pathArray.length; p++) {
  36745. for (i = 0; i < minlg + closePathCorr; i++) {
  36746. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36747. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36748. if (invertUV) {
  36749. uvs.push(v, u);
  36750. }
  36751. else {
  36752. uvs.push(u, v);
  36753. }
  36754. }
  36755. }
  36756. }
  36757. // indices
  36758. p = 0; // path index
  36759. var pi = 0; // positions array index
  36760. var l1 = lg[p] - 1; // path1 length
  36761. var l2 = lg[p + 1] - 1; // path2 length
  36762. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36763. var shft = idx[1] - idx[0]; // shift
  36764. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36765. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36766. // 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
  36767. indices.push(pi, pi + shft, pi + 1);
  36768. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36769. pi += 1;
  36770. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36771. p++;
  36772. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36773. shft = idx[0] - idx[p];
  36774. l1 = lg[p] - 1;
  36775. l2 = lg[0] - 1;
  36776. }
  36777. else {
  36778. shft = idx[p + 1] - idx[p];
  36779. l1 = lg[p] - 1;
  36780. l2 = lg[p + 1] - 1;
  36781. }
  36782. pi = idx[p];
  36783. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36784. }
  36785. }
  36786. // normals
  36787. VertexData.ComputeNormals(positions, indices, normals);
  36788. if (closePath) { // update both the first and last vertex normals to their average value
  36789. var indexFirst = 0;
  36790. var indexLast = 0;
  36791. for (p = 0; p < pathArray.length; p++) {
  36792. indexFirst = idx[p] * 3;
  36793. if (p + 1 < pathArray.length) {
  36794. indexLast = (idx[p + 1] - 1) * 3;
  36795. }
  36796. else {
  36797. indexLast = normals.length - 3;
  36798. }
  36799. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36800. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36801. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36802. normals[indexLast] = normals[indexFirst];
  36803. normals[indexLast + 1] = normals[indexFirst + 1];
  36804. normals[indexLast + 2] = normals[indexFirst + 2];
  36805. }
  36806. }
  36807. // sides
  36808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36809. // Colors
  36810. var colors = null;
  36811. if (customColors) {
  36812. colors = new Float32Array(customColors.length * 4);
  36813. for (var c = 0; c < customColors.length; c++) {
  36814. colors[c * 4] = customColors[c].r;
  36815. colors[c * 4 + 1] = customColors[c].g;
  36816. colors[c * 4 + 2] = customColors[c].b;
  36817. colors[c * 4 + 3] = customColors[c].a;
  36818. }
  36819. }
  36820. // Result
  36821. var vertexData = new VertexData();
  36822. var positions32 = new Float32Array(positions);
  36823. var normals32 = new Float32Array(normals);
  36824. var uvs32 = new Float32Array(uvs);
  36825. vertexData.indices = indices;
  36826. vertexData.positions = positions32;
  36827. vertexData.normals = normals32;
  36828. vertexData.uvs = uvs32;
  36829. if (colors) {
  36830. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36831. }
  36832. if (closePath) {
  36833. vertexData._idx = idx;
  36834. }
  36835. return vertexData;
  36836. };
  36837. /**
  36838. * Creates the VertexData for a box
  36839. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36840. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36841. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36842. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36843. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36844. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36845. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36846. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36847. * * 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)
  36848. * * 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)
  36849. * @returns the VertexData of the box
  36850. */
  36851. VertexData.CreateBox = function (options) {
  36852. var normalsSource = [
  36853. new BABYLON.Vector3(0, 0, 1),
  36854. new BABYLON.Vector3(0, 0, -1),
  36855. new BABYLON.Vector3(1, 0, 0),
  36856. new BABYLON.Vector3(-1, 0, 0),
  36857. new BABYLON.Vector3(0, 1, 0),
  36858. new BABYLON.Vector3(0, -1, 0)
  36859. ];
  36860. var indices = [];
  36861. var positions = [];
  36862. var normals = [];
  36863. var uvs = [];
  36864. var width = options.width || options.size || 1;
  36865. var height = options.height || options.size || 1;
  36866. var depth = options.depth || options.size || 1;
  36867. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36868. var faceUV = options.faceUV || new Array(6);
  36869. var faceColors = options.faceColors;
  36870. var colors = [];
  36871. // default face colors and UV if undefined
  36872. for (var f = 0; f < 6; f++) {
  36873. if (faceUV[f] === undefined) {
  36874. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36875. }
  36876. if (faceColors && faceColors[f] === undefined) {
  36877. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36878. }
  36879. }
  36880. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36881. // Create each face in turn.
  36882. for (var index = 0; index < normalsSource.length; index++) {
  36883. var normal = normalsSource[index];
  36884. // Get two vectors perpendicular to the face normal and to each other.
  36885. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36886. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36887. // Six indices (two triangles) per face.
  36888. var verticesLength = positions.length / 3;
  36889. indices.push(verticesLength);
  36890. indices.push(verticesLength + 1);
  36891. indices.push(verticesLength + 2);
  36892. indices.push(verticesLength);
  36893. indices.push(verticesLength + 2);
  36894. indices.push(verticesLength + 3);
  36895. // Four vertices per face.
  36896. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36897. positions.push(vertex.x, vertex.y, vertex.z);
  36898. normals.push(normal.x, normal.y, normal.z);
  36899. uvs.push(faceUV[index].z, faceUV[index].w);
  36900. if (faceColors) {
  36901. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36902. }
  36903. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36904. positions.push(vertex.x, vertex.y, vertex.z);
  36905. normals.push(normal.x, normal.y, normal.z);
  36906. uvs.push(faceUV[index].x, faceUV[index].w);
  36907. if (faceColors) {
  36908. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36909. }
  36910. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36911. positions.push(vertex.x, vertex.y, vertex.z);
  36912. normals.push(normal.x, normal.y, normal.z);
  36913. uvs.push(faceUV[index].x, faceUV[index].y);
  36914. if (faceColors) {
  36915. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36916. }
  36917. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36918. positions.push(vertex.x, vertex.y, vertex.z);
  36919. normals.push(normal.x, normal.y, normal.z);
  36920. uvs.push(faceUV[index].z, faceUV[index].y);
  36921. if (faceColors) {
  36922. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36923. }
  36924. }
  36925. // sides
  36926. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36927. // Result
  36928. var vertexData = new VertexData();
  36929. vertexData.indices = indices;
  36930. vertexData.positions = positions;
  36931. vertexData.normals = normals;
  36932. vertexData.uvs = uvs;
  36933. if (faceColors) {
  36934. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36935. vertexData.colors = totalColors;
  36936. }
  36937. return vertexData;
  36938. };
  36939. /**
  36940. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36941. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36942. * * segments sets the number of horizontal strips optional, default 32
  36943. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36944. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36945. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36946. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36947. * * 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
  36948. * * 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
  36949. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36950. * * 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)
  36951. * * 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)
  36952. * @returns the VertexData of the ellipsoid
  36953. */
  36954. VertexData.CreateSphere = function (options) {
  36955. var segments = options.segments || 32;
  36956. var diameterX = options.diameterX || options.diameter || 1;
  36957. var diameterY = options.diameterY || options.diameter || 1;
  36958. var diameterZ = options.diameterZ || options.diameter || 1;
  36959. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36960. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36961. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36962. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36963. var totalZRotationSteps = 2 + segments;
  36964. var totalYRotationSteps = 2 * totalZRotationSteps;
  36965. var indices = [];
  36966. var positions = [];
  36967. var normals = [];
  36968. var uvs = [];
  36969. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36970. var normalizedZ = zRotationStep / totalZRotationSteps;
  36971. var angleZ = normalizedZ * Math.PI * slice;
  36972. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36973. var normalizedY = yRotationStep / totalYRotationSteps;
  36974. var angleY = normalizedY * Math.PI * 2 * arc;
  36975. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36976. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36977. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36978. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36979. var vertex = complete.multiply(radius);
  36980. var normal = complete.divide(radius).normalize();
  36981. positions.push(vertex.x, vertex.y, vertex.z);
  36982. normals.push(normal.x, normal.y, normal.z);
  36983. uvs.push(normalizedY, normalizedZ);
  36984. }
  36985. if (zRotationStep > 0) {
  36986. var verticesCount = positions.length / 3;
  36987. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36988. indices.push((firstIndex));
  36989. indices.push((firstIndex + 1));
  36990. indices.push(firstIndex + totalYRotationSteps + 1);
  36991. indices.push((firstIndex + totalYRotationSteps + 1));
  36992. indices.push((firstIndex + 1));
  36993. indices.push((firstIndex + totalYRotationSteps + 2));
  36994. }
  36995. }
  36996. }
  36997. // Sides
  36998. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36999. // Result
  37000. var vertexData = new VertexData();
  37001. vertexData.indices = indices;
  37002. vertexData.positions = positions;
  37003. vertexData.normals = normals;
  37004. vertexData.uvs = uvs;
  37005. return vertexData;
  37006. };
  37007. /**
  37008. * Creates the VertexData for a cylinder, cone or prism
  37009. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37010. * * height sets the height (y direction) of the cylinder, optional, default 2
  37011. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37012. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37013. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37014. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37015. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37016. * * 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
  37017. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37018. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37019. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37020. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37021. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37022. * * 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)
  37023. * * 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)
  37024. * @returns the VertexData of the cylinder, cone or prism
  37025. */
  37026. VertexData.CreateCylinder = function (options) {
  37027. var height = options.height || 2;
  37028. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37029. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37030. var tessellation = options.tessellation || 24;
  37031. var subdivisions = options.subdivisions || 1;
  37032. var hasRings = options.hasRings ? true : false;
  37033. var enclose = options.enclose ? true : false;
  37034. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37035. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37036. var faceUV = options.faceUV || new Array(3);
  37037. var faceColors = options.faceColors;
  37038. // default face colors and UV if undefined
  37039. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37040. var ringNb = (hasRings) ? subdivisions : 1;
  37041. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37042. var f;
  37043. for (f = 0; f < surfaceNb; f++) {
  37044. if (faceColors && faceColors[f] === undefined) {
  37045. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37046. }
  37047. }
  37048. for (f = 0; f < surfaceNb; f++) {
  37049. if (faceUV && faceUV[f] === undefined) {
  37050. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37051. }
  37052. }
  37053. var indices = new Array();
  37054. var positions = new Array();
  37055. var normals = new Array();
  37056. var uvs = new Array();
  37057. var colors = new Array();
  37058. var angle_step = Math.PI * 2 * arc / tessellation;
  37059. var angle;
  37060. var h;
  37061. var radius;
  37062. var tan = (diameterBottom - diameterTop) / 2 / height;
  37063. var ringVertex = BABYLON.Vector3.Zero();
  37064. var ringNormal = BABYLON.Vector3.Zero();
  37065. var ringFirstVertex = BABYLON.Vector3.Zero();
  37066. var ringFirstNormal = BABYLON.Vector3.Zero();
  37067. var quadNormal = BABYLON.Vector3.Zero();
  37068. var Y = BABYLON.Axis.Y;
  37069. // positions, normals, uvs
  37070. var i;
  37071. var j;
  37072. var r;
  37073. var ringIdx = 1;
  37074. var s = 1; // surface index
  37075. var cs = 0;
  37076. var v = 0;
  37077. for (i = 0; i <= subdivisions; i++) {
  37078. h = i / subdivisions;
  37079. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37080. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37081. for (r = 0; r < ringIdx; r++) {
  37082. if (hasRings) {
  37083. s += r;
  37084. }
  37085. if (enclose) {
  37086. s += 2 * r;
  37087. }
  37088. for (j = 0; j <= tessellation; j++) {
  37089. angle = j * angle_step;
  37090. // position
  37091. ringVertex.x = Math.cos(-angle) * radius;
  37092. ringVertex.y = -height / 2 + h * height;
  37093. ringVertex.z = Math.sin(-angle) * radius;
  37094. // normal
  37095. if (diameterTop === 0 && i === subdivisions) {
  37096. // if no top cap, reuse former normals
  37097. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37098. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37099. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37100. }
  37101. else {
  37102. ringNormal.x = ringVertex.x;
  37103. ringNormal.z = ringVertex.z;
  37104. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37105. ringNormal.normalize();
  37106. }
  37107. // keep first ring vertex values for enclose
  37108. if (j === 0) {
  37109. ringFirstVertex.copyFrom(ringVertex);
  37110. ringFirstNormal.copyFrom(ringNormal);
  37111. }
  37112. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37113. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37114. if (hasRings) {
  37115. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37116. }
  37117. else {
  37118. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37119. }
  37120. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37121. if (faceColors) {
  37122. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37123. }
  37124. }
  37125. // if enclose, add four vertices and their dedicated normals
  37126. if (arc !== 1 && enclose) {
  37127. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37128. positions.push(0, ringVertex.y, 0);
  37129. positions.push(0, ringVertex.y, 0);
  37130. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37131. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37132. quadNormal.normalize();
  37133. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37134. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37135. quadNormal.normalize();
  37136. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37137. if (hasRings) {
  37138. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37139. }
  37140. else {
  37141. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37142. }
  37143. uvs.push(faceUV[s + 1].x, v);
  37144. uvs.push(faceUV[s + 1].z, v);
  37145. if (hasRings) {
  37146. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37147. }
  37148. else {
  37149. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37150. }
  37151. uvs.push(faceUV[s + 2].x, v);
  37152. uvs.push(faceUV[s + 2].z, v);
  37153. if (faceColors) {
  37154. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37155. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37156. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37157. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37158. }
  37159. }
  37160. if (cs !== s) {
  37161. cs = s;
  37162. }
  37163. }
  37164. }
  37165. // indices
  37166. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37167. var s;
  37168. i = 0;
  37169. for (s = 0; s < subdivisions; s++) {
  37170. var i0 = 0;
  37171. var i1 = 0;
  37172. var i2 = 0;
  37173. var i3 = 0;
  37174. for (j = 0; j < tessellation; j++) {
  37175. i0 = i * (e + 1) + j;
  37176. i1 = (i + 1) * (e + 1) + j;
  37177. i2 = i * (e + 1) + (j + 1);
  37178. i3 = (i + 1) * (e + 1) + (j + 1);
  37179. indices.push(i0, i1, i2);
  37180. indices.push(i3, i2, i1);
  37181. }
  37182. if (arc !== 1 && enclose) { // if enclose, add two quads
  37183. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37184. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37185. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37186. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37187. }
  37188. i = (hasRings) ? (i + 2) : (i + 1);
  37189. }
  37190. // Caps
  37191. var createCylinderCap = function (isTop) {
  37192. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37193. if (radius === 0) {
  37194. return;
  37195. }
  37196. // Cap positions, normals & uvs
  37197. var angle;
  37198. var circleVector;
  37199. var i;
  37200. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37201. var c = null;
  37202. if (faceColors) {
  37203. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37204. }
  37205. // cap center
  37206. var vbase = positions.length / 3;
  37207. var offset = isTop ? height / 2 : -height / 2;
  37208. var center = new BABYLON.Vector3(0, offset, 0);
  37209. positions.push(center.x, center.y, center.z);
  37210. normals.push(0, isTop ? 1 : -1, 0);
  37211. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37212. if (c) {
  37213. colors.push(c.r, c.g, c.b, c.a);
  37214. }
  37215. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37216. for (i = 0; i <= tessellation; i++) {
  37217. angle = Math.PI * 2 * i * arc / tessellation;
  37218. var cos = Math.cos(-angle);
  37219. var sin = Math.sin(-angle);
  37220. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37221. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37222. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37223. normals.push(0, isTop ? 1 : -1, 0);
  37224. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37225. if (c) {
  37226. colors.push(c.r, c.g, c.b, c.a);
  37227. }
  37228. }
  37229. // Cap indices
  37230. for (i = 0; i < tessellation; i++) {
  37231. if (!isTop) {
  37232. indices.push(vbase);
  37233. indices.push(vbase + (i + 1));
  37234. indices.push(vbase + (i + 2));
  37235. }
  37236. else {
  37237. indices.push(vbase);
  37238. indices.push(vbase + (i + 2));
  37239. indices.push(vbase + (i + 1));
  37240. }
  37241. }
  37242. };
  37243. // add caps to geometry
  37244. createCylinderCap(false);
  37245. createCylinderCap(true);
  37246. // Sides
  37247. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37248. var vertexData = new VertexData();
  37249. vertexData.indices = indices;
  37250. vertexData.positions = positions;
  37251. vertexData.normals = normals;
  37252. vertexData.uvs = uvs;
  37253. if (faceColors) {
  37254. vertexData.colors = colors;
  37255. }
  37256. return vertexData;
  37257. };
  37258. /**
  37259. * Creates the VertexData for a torus
  37260. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37261. * * diameter the diameter of the torus, optional default 1
  37262. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37263. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37264. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37265. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37266. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37267. * @returns the VertexData of the torus
  37268. */
  37269. VertexData.CreateTorus = function (options) {
  37270. var indices = [];
  37271. var positions = [];
  37272. var normals = [];
  37273. var uvs = [];
  37274. var diameter = options.diameter || 1;
  37275. var thickness = options.thickness || 0.5;
  37276. var tessellation = options.tessellation || 16;
  37277. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37278. var stride = tessellation + 1;
  37279. for (var i = 0; i <= tessellation; i++) {
  37280. var u = i / tessellation;
  37281. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37282. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37283. for (var j = 0; j <= tessellation; j++) {
  37284. var v = 1 - j / tessellation;
  37285. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37286. var dx = Math.cos(innerAngle);
  37287. var dy = Math.sin(innerAngle);
  37288. // Create a vertex.
  37289. var normal = new BABYLON.Vector3(dx, dy, 0);
  37290. var position = normal.scale(thickness / 2);
  37291. var textureCoordinate = new BABYLON.Vector2(u, v);
  37292. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37293. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37294. positions.push(position.x, position.y, position.z);
  37295. normals.push(normal.x, normal.y, normal.z);
  37296. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37297. // And create indices for two triangles.
  37298. var nextI = (i + 1) % stride;
  37299. var nextJ = (j + 1) % stride;
  37300. indices.push(i * stride + j);
  37301. indices.push(i * stride + nextJ);
  37302. indices.push(nextI * stride + j);
  37303. indices.push(i * stride + nextJ);
  37304. indices.push(nextI * stride + nextJ);
  37305. indices.push(nextI * stride + j);
  37306. }
  37307. }
  37308. // Sides
  37309. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37310. // Result
  37311. var vertexData = new VertexData();
  37312. vertexData.indices = indices;
  37313. vertexData.positions = positions;
  37314. vertexData.normals = normals;
  37315. vertexData.uvs = uvs;
  37316. return vertexData;
  37317. };
  37318. /**
  37319. * Creates the VertexData of the LineSystem
  37320. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37321. * - lines an array of lines, each line being an array of successive Vector3
  37322. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37323. * @returns the VertexData of the LineSystem
  37324. */
  37325. VertexData.CreateLineSystem = function (options) {
  37326. var indices = [];
  37327. var positions = [];
  37328. var lines = options.lines;
  37329. var colors = options.colors;
  37330. var vertexColors = [];
  37331. var idx = 0;
  37332. for (var l = 0; l < lines.length; l++) {
  37333. var points = lines[l];
  37334. for (var index = 0; index < points.length; index++) {
  37335. positions.push(points[index].x, points[index].y, points[index].z);
  37336. if (colors) {
  37337. var color = colors[l];
  37338. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37339. }
  37340. if (index > 0) {
  37341. indices.push(idx - 1);
  37342. indices.push(idx);
  37343. }
  37344. idx++;
  37345. }
  37346. }
  37347. var vertexData = new VertexData();
  37348. vertexData.indices = indices;
  37349. vertexData.positions = positions;
  37350. if (colors) {
  37351. vertexData.colors = vertexColors;
  37352. }
  37353. return vertexData;
  37354. };
  37355. /**
  37356. * Create the VertexData for a DashedLines
  37357. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37358. * - points an array successive Vector3
  37359. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37360. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37361. * - dashNb the intended total number of dashes, optional, default 200
  37362. * @returns the VertexData for the DashedLines
  37363. */
  37364. VertexData.CreateDashedLines = function (options) {
  37365. var dashSize = options.dashSize || 3;
  37366. var gapSize = options.gapSize || 1;
  37367. var dashNb = options.dashNb || 200;
  37368. var points = options.points;
  37369. var positions = new Array();
  37370. var indices = new Array();
  37371. var curvect = BABYLON.Vector3.Zero();
  37372. var lg = 0;
  37373. var nb = 0;
  37374. var shft = 0;
  37375. var dashshft = 0;
  37376. var curshft = 0;
  37377. var idx = 0;
  37378. var i = 0;
  37379. for (i = 0; i < points.length - 1; i++) {
  37380. points[i + 1].subtractToRef(points[i], curvect);
  37381. lg += curvect.length();
  37382. }
  37383. shft = lg / dashNb;
  37384. dashshft = dashSize * shft / (dashSize + gapSize);
  37385. for (i = 0; i < points.length - 1; i++) {
  37386. points[i + 1].subtractToRef(points[i], curvect);
  37387. nb = Math.floor(curvect.length() / shft);
  37388. curvect.normalize();
  37389. for (var j = 0; j < nb; j++) {
  37390. curshft = shft * j;
  37391. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37392. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37393. indices.push(idx, idx + 1);
  37394. idx += 2;
  37395. }
  37396. }
  37397. // Result
  37398. var vertexData = new VertexData();
  37399. vertexData.positions = positions;
  37400. vertexData.indices = indices;
  37401. return vertexData;
  37402. };
  37403. /**
  37404. * Creates the VertexData for a Ground
  37405. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37406. * - width the width (x direction) of the ground, optional, default 1
  37407. * - height the height (z direction) of the ground, optional, default 1
  37408. * - subdivisions the number of subdivisions per side, optional, default 1
  37409. * @returns the VertexData of the Ground
  37410. */
  37411. VertexData.CreateGround = function (options) {
  37412. var indices = [];
  37413. var positions = [];
  37414. var normals = [];
  37415. var uvs = [];
  37416. var row, col;
  37417. var width = options.width || 1;
  37418. var height = options.height || 1;
  37419. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37420. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37421. for (row = 0; row <= subdivisionsY; row++) {
  37422. for (col = 0; col <= subdivisionsX; col++) {
  37423. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37424. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37425. positions.push(position.x, position.y, position.z);
  37426. normals.push(normal.x, normal.y, normal.z);
  37427. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37428. }
  37429. }
  37430. for (row = 0; row < subdivisionsY; row++) {
  37431. for (col = 0; col < subdivisionsX; col++) {
  37432. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37433. indices.push(col + 1 + row * (subdivisionsX + 1));
  37434. indices.push(col + row * (subdivisionsX + 1));
  37435. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37436. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37437. indices.push(col + row * (subdivisionsX + 1));
  37438. }
  37439. }
  37440. // Result
  37441. var vertexData = new VertexData();
  37442. vertexData.indices = indices;
  37443. vertexData.positions = positions;
  37444. vertexData.normals = normals;
  37445. vertexData.uvs = uvs;
  37446. return vertexData;
  37447. };
  37448. /**
  37449. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37450. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37451. * * xmin the ground minimum X coordinate, optional, default -1
  37452. * * zmin the ground minimum Z coordinate, optional, default -1
  37453. * * xmax the ground maximum X coordinate, optional, default 1
  37454. * * zmax the ground maximum Z coordinate, optional, default 1
  37455. * * 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}
  37456. * * 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}
  37457. * @returns the VertexData of the TiledGround
  37458. */
  37459. VertexData.CreateTiledGround = function (options) {
  37460. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37461. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37462. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37463. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37464. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37465. var precision = options.precision || { w: 1, h: 1 };
  37466. var indices = new Array();
  37467. var positions = new Array();
  37468. var normals = new Array();
  37469. var uvs = new Array();
  37470. var row, col, tileRow, tileCol;
  37471. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37472. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37473. precision.w = (precision.w < 1) ? 1 : precision.w;
  37474. precision.h = (precision.h < 1) ? 1 : precision.h;
  37475. var tileSize = {
  37476. 'w': (xmax - xmin) / subdivisions.w,
  37477. 'h': (zmax - zmin) / subdivisions.h
  37478. };
  37479. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37480. // Indices
  37481. var base = positions.length / 3;
  37482. var rowLength = precision.w + 1;
  37483. for (row = 0; row < precision.h; row++) {
  37484. for (col = 0; col < precision.w; col++) {
  37485. var square = [
  37486. base + col + row * rowLength,
  37487. base + (col + 1) + row * rowLength,
  37488. base + (col + 1) + (row + 1) * rowLength,
  37489. base + col + (row + 1) * rowLength
  37490. ];
  37491. indices.push(square[1]);
  37492. indices.push(square[2]);
  37493. indices.push(square[3]);
  37494. indices.push(square[0]);
  37495. indices.push(square[1]);
  37496. indices.push(square[3]);
  37497. }
  37498. }
  37499. // Position, normals and uvs
  37500. var position = BABYLON.Vector3.Zero();
  37501. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37502. for (row = 0; row <= precision.h; row++) {
  37503. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37504. for (col = 0; col <= precision.w; col++) {
  37505. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37506. position.y = 0;
  37507. positions.push(position.x, position.y, position.z);
  37508. normals.push(normal.x, normal.y, normal.z);
  37509. uvs.push(col / precision.w, row / precision.h);
  37510. }
  37511. }
  37512. }
  37513. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37514. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37515. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37516. }
  37517. }
  37518. // Result
  37519. var vertexData = new VertexData();
  37520. vertexData.indices = indices;
  37521. vertexData.positions = positions;
  37522. vertexData.normals = normals;
  37523. vertexData.uvs = uvs;
  37524. return vertexData;
  37525. };
  37526. /**
  37527. * Creates the VertexData of the Ground designed from a heightmap
  37528. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37529. * * width the width (x direction) of the ground
  37530. * * height the height (z direction) of the ground
  37531. * * subdivisions the number of subdivisions per side
  37532. * * minHeight the minimum altitude on the ground, optional, default 0
  37533. * * maxHeight the maximum altitude on the ground, optional default 1
  37534. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37535. * * buffer the array holding the image color data
  37536. * * bufferWidth the width of image
  37537. * * bufferHeight the height of image
  37538. * @returns the VertexData of the Ground designed from a heightmap
  37539. */
  37540. VertexData.CreateGroundFromHeightMap = function (options) {
  37541. var indices = [];
  37542. var positions = [];
  37543. var normals = [];
  37544. var uvs = [];
  37545. var row, col;
  37546. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37547. // Vertices
  37548. for (row = 0; row <= options.subdivisions; row++) {
  37549. for (col = 0; col <= options.subdivisions; col++) {
  37550. 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));
  37551. // Compute height
  37552. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37553. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37554. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37555. var r = options.buffer[pos] / 255.0;
  37556. var g = options.buffer[pos + 1] / 255.0;
  37557. var b = options.buffer[pos + 2] / 255.0;
  37558. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37559. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37560. // Add vertex
  37561. positions.push(position.x, position.y, position.z);
  37562. normals.push(0, 0, 0);
  37563. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37564. }
  37565. }
  37566. // Indices
  37567. for (row = 0; row < options.subdivisions; row++) {
  37568. for (col = 0; col < options.subdivisions; col++) {
  37569. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37570. indices.push(col + 1 + row * (options.subdivisions + 1));
  37571. indices.push(col + row * (options.subdivisions + 1));
  37572. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37573. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37574. indices.push(col + row * (options.subdivisions + 1));
  37575. }
  37576. }
  37577. // Normals
  37578. VertexData.ComputeNormals(positions, indices, normals);
  37579. // Result
  37580. var vertexData = new VertexData();
  37581. vertexData.indices = indices;
  37582. vertexData.positions = positions;
  37583. vertexData.normals = normals;
  37584. vertexData.uvs = uvs;
  37585. return vertexData;
  37586. };
  37587. /**
  37588. * Creates the VertexData for a Plane
  37589. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37590. * * size sets the width and height of the plane to the value of size, optional default 1
  37591. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37592. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37593. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37594. * * 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)
  37595. * * 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)
  37596. * @returns the VertexData of the box
  37597. */
  37598. VertexData.CreatePlane = function (options) {
  37599. var indices = [];
  37600. var positions = [];
  37601. var normals = [];
  37602. var uvs = [];
  37603. var width = options.width || options.size || 1;
  37604. var height = options.height || options.size || 1;
  37605. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37606. // Vertices
  37607. var halfWidth = width / 2.0;
  37608. var halfHeight = height / 2.0;
  37609. positions.push(-halfWidth, -halfHeight, 0);
  37610. normals.push(0, 0, -1.0);
  37611. uvs.push(0.0, 0.0);
  37612. positions.push(halfWidth, -halfHeight, 0);
  37613. normals.push(0, 0, -1.0);
  37614. uvs.push(1.0, 0.0);
  37615. positions.push(halfWidth, halfHeight, 0);
  37616. normals.push(0, 0, -1.0);
  37617. uvs.push(1.0, 1.0);
  37618. positions.push(-halfWidth, halfHeight, 0);
  37619. normals.push(0, 0, -1.0);
  37620. uvs.push(0.0, 1.0);
  37621. // Indices
  37622. indices.push(0);
  37623. indices.push(1);
  37624. indices.push(2);
  37625. indices.push(0);
  37626. indices.push(2);
  37627. indices.push(3);
  37628. // Sides
  37629. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37630. // Result
  37631. var vertexData = new VertexData();
  37632. vertexData.indices = indices;
  37633. vertexData.positions = positions;
  37634. vertexData.normals = normals;
  37635. vertexData.uvs = uvs;
  37636. return vertexData;
  37637. };
  37638. /**
  37639. * Creates the VertexData of the Disc or regular Polygon
  37640. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37641. * * radius the radius of the disc, optional default 0.5
  37642. * * tessellation the number of polygon sides, optional, default 64
  37643. * * 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
  37644. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37645. * * 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)
  37646. * * 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)
  37647. * @returns the VertexData of the box
  37648. */
  37649. VertexData.CreateDisc = function (options) {
  37650. var positions = new Array();
  37651. var indices = new Array();
  37652. var normals = new Array();
  37653. var uvs = new Array();
  37654. var radius = options.radius || 0.5;
  37655. var tessellation = options.tessellation || 64;
  37656. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37657. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37658. // positions and uvs
  37659. positions.push(0, 0, 0); // disc center first
  37660. uvs.push(0.5, 0.5);
  37661. var theta = Math.PI * 2 * arc;
  37662. var step = theta / tessellation;
  37663. for (var a = 0; a < theta; a += step) {
  37664. var x = Math.cos(a);
  37665. var y = Math.sin(a);
  37666. var u = (x + 1) / 2;
  37667. var v = (1 - y) / 2;
  37668. positions.push(radius * x, radius * y, 0);
  37669. uvs.push(u, v);
  37670. }
  37671. if (arc === 1) {
  37672. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37673. uvs.push(uvs[2], uvs[3]);
  37674. }
  37675. //indices
  37676. var vertexNb = positions.length / 3;
  37677. for (var i = 1; i < vertexNb - 1; i++) {
  37678. indices.push(i + 1, 0, i);
  37679. }
  37680. // result
  37681. VertexData.ComputeNormals(positions, indices, normals);
  37682. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37683. var vertexData = new VertexData();
  37684. vertexData.indices = indices;
  37685. vertexData.positions = positions;
  37686. vertexData.normals = normals;
  37687. vertexData.uvs = uvs;
  37688. return vertexData;
  37689. };
  37690. /**
  37691. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37692. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37693. * @param polygon a mesh built from polygonTriangulation.build()
  37694. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37695. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37696. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37697. * @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)
  37698. * @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)
  37699. * @returns the VertexData of the Polygon
  37700. */
  37701. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37702. var faceUV = fUV || new Array(3);
  37703. var faceColors = fColors;
  37704. var colors = [];
  37705. // default face colors and UV if undefined
  37706. for (var f = 0; f < 3; f++) {
  37707. if (faceUV[f] === undefined) {
  37708. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37709. }
  37710. if (faceColors && faceColors[f] === undefined) {
  37711. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37712. }
  37713. }
  37714. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37715. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37716. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37717. var indices = polygon.getIndices();
  37718. // set face colours and textures
  37719. var idx = 0;
  37720. var face = 0;
  37721. for (var index = 0; index < normals.length; index += 3) {
  37722. //Edge Face no. 1
  37723. if (Math.abs(normals[index + 1]) < 0.001) {
  37724. face = 1;
  37725. }
  37726. //Top Face no. 0
  37727. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37728. face = 0;
  37729. }
  37730. //Bottom Face no. 2
  37731. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37732. face = 2;
  37733. }
  37734. idx = index / 3;
  37735. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37736. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37737. if (faceColors) {
  37738. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37739. }
  37740. }
  37741. // sides
  37742. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37743. // Result
  37744. var vertexData = new VertexData();
  37745. vertexData.indices = indices;
  37746. vertexData.positions = positions;
  37747. vertexData.normals = normals;
  37748. vertexData.uvs = uvs;
  37749. if (faceColors) {
  37750. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37751. vertexData.colors = totalColors;
  37752. }
  37753. return vertexData;
  37754. };
  37755. /**
  37756. * Creates the VertexData of the IcoSphere
  37757. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37758. * * radius the radius of the IcoSphere, optional default 1
  37759. * * radiusX allows stretching in the x direction, optional, default radius
  37760. * * radiusY allows stretching in the y direction, optional, default radius
  37761. * * radiusZ allows stretching in the z direction, optional, default radius
  37762. * * flat when true creates a flat shaded mesh, optional, default true
  37763. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37764. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37765. * * 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)
  37766. * * 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)
  37767. * @returns the VertexData of the IcoSphere
  37768. */
  37769. VertexData.CreateIcoSphere = function (options) {
  37770. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37771. var radius = options.radius || 1;
  37772. var flat = (options.flat === undefined) ? true : options.flat;
  37773. var subdivisions = options.subdivisions || 4;
  37774. var radiusX = options.radiusX || radius;
  37775. var radiusY = options.radiusY || radius;
  37776. var radiusZ = options.radiusZ || radius;
  37777. var t = (1 + Math.sqrt(5)) / 2;
  37778. // 12 vertex x,y,z
  37779. var ico_vertices = [
  37780. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37781. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37782. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37783. ];
  37784. // index of 3 vertex makes a face of icopshere
  37785. var ico_indices = [
  37786. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37787. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37788. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37789. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37790. ];
  37791. // vertex for uv have aliased position, not for UV
  37792. var vertices_unalias_id = [
  37793. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37794. // vertex alias
  37795. 0,
  37796. 2,
  37797. 3,
  37798. 3,
  37799. 3,
  37800. 4,
  37801. 7,
  37802. 8,
  37803. 9,
  37804. 9,
  37805. 10,
  37806. 11 // 23: B + 12
  37807. ];
  37808. // uv as integer step (not pixels !)
  37809. var ico_vertexuv = [
  37810. 5, 1, 3, 1, 6, 4, 0, 0,
  37811. 5, 3, 4, 2, 2, 2, 4, 0,
  37812. 2, 0, 1, 1, 6, 0, 6, 2,
  37813. // vertex alias (for same vertex on different faces)
  37814. 0, 4,
  37815. 3, 3,
  37816. 4, 4,
  37817. 3, 1,
  37818. 4, 2,
  37819. 4, 4,
  37820. 0, 2,
  37821. 1, 1,
  37822. 2, 2,
  37823. 3, 3,
  37824. 1, 3,
  37825. 2, 4 // 23: B + 12
  37826. ];
  37827. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37828. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37829. // First island of uv mapping
  37830. // v = 4h 3+ 2
  37831. // v = 3h 9+ 4
  37832. // v = 2h 9+ 5 B
  37833. // v = 1h 9 1 0
  37834. // v = 0h 3 8 7 A
  37835. // u = 0 1 2 3 4 5 6 *a
  37836. // Second island of uv mapping
  37837. // v = 4h 0+ B+ 4+
  37838. // v = 3h A+ 2+
  37839. // v = 2h 7+ 6 3+
  37840. // v = 1h 8+ 3+
  37841. // v = 0h
  37842. // u = 0 1 2 3 4 5 6 *a
  37843. // Face layout on texture UV mapping
  37844. // ============
  37845. // \ 4 /\ 16 / ======
  37846. // \ / \ / /\ 11 /
  37847. // \/ 7 \/ / \ /
  37848. // ======= / 10 \/
  37849. // /\ 17 /\ =======
  37850. // / \ / \ \ 15 /\
  37851. // / 8 \/ 12 \ \ / \
  37852. // ============ \/ 6 \
  37853. // \ 18 /\ ============
  37854. // \ / \ \ 5 /\ 0 /
  37855. // \/ 13 \ \ / \ /
  37856. // ======= \/ 1 \/
  37857. // =============
  37858. // /\ 19 /\ 2 /\
  37859. // / \ / \ / \
  37860. // / 14 \/ 9 \/ 3 \
  37861. // ===================
  37862. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37863. var ustep = 138 / 1024;
  37864. var vstep = 239 / 1024;
  37865. var uoffset = 60 / 1024;
  37866. var voffset = 26 / 1024;
  37867. // Second island should have margin, not to touch the first island
  37868. // avoid any borderline artefact in pixel rounding
  37869. var island_u_offset = -40 / 1024;
  37870. var island_v_offset = +20 / 1024;
  37871. // face is either island 0 or 1 :
  37872. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37873. var island = [
  37874. 0, 0, 0, 0, 1,
  37875. 0, 0, 1, 1, 0,
  37876. 0, 0, 1, 1, 0,
  37877. 0, 1, 1, 1, 0 // 15 - 19
  37878. ];
  37879. var indices = new Array();
  37880. var positions = new Array();
  37881. var normals = new Array();
  37882. var uvs = new Array();
  37883. var current_indice = 0;
  37884. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37885. var face_vertex_pos = new Array(3);
  37886. var face_vertex_uv = new Array(3);
  37887. var v012;
  37888. for (v012 = 0; v012 < 3; v012++) {
  37889. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37890. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37891. }
  37892. // create all with normals
  37893. for (var face = 0; face < 20; face++) {
  37894. // 3 vertex per face
  37895. for (v012 = 0; v012 < 3; v012++) {
  37896. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37897. var v_id = ico_indices[3 * face + v012];
  37898. // vertex have 3D position (x,y,z)
  37899. 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]);
  37900. // Normalize to get normal, then scale to radius
  37901. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37902. // uv Coordinates from vertex ID
  37903. 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);
  37904. }
  37905. // Subdivide the face (interpolate pos, norm, uv)
  37906. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37907. // - norm is linear interpolation of vertex corner normal
  37908. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37909. // - uv is linear interpolation
  37910. //
  37911. // Topology is as below for sub-divide by 2
  37912. // vertex shown as v0,v1,v2
  37913. // interp index is i1 to progress in range [v0,v1[
  37914. // interp index is i2 to progress in range [v0,v2[
  37915. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37916. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37917. //
  37918. //
  37919. // i2 v2
  37920. // ^ ^
  37921. // / / \
  37922. // / / \
  37923. // / / \
  37924. // / / (0,1) \
  37925. // / #---------\
  37926. // / / \ (0,0)'/ \
  37927. // / / \ / \
  37928. // / / \ / \
  37929. // / / (0,0) \ / (1,0) \
  37930. // / #---------#---------\
  37931. // v0 v1
  37932. //
  37933. // --------------------> i1
  37934. //
  37935. // interp of (i1,i2):
  37936. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37937. // along i1 : lerp(x0,x1, i1/(S-i2))
  37938. //
  37939. // centroid of triangle is needed to get help normal computation
  37940. // (c1,c2) are used for centroid location
  37941. var interp_vertex = function (i1, i2, c1, c2) {
  37942. // vertex is interpolated from
  37943. // - face_vertex_pos[0..2]
  37944. // - face_vertex_uv[0..2]
  37945. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37946. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37947. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37948. pos_interp.normalize();
  37949. var vertex_normal;
  37950. if (flat) {
  37951. // in flat mode, recalculate normal as face centroid normal
  37952. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37953. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37954. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37955. }
  37956. else {
  37957. // in smooth mode, recalculate normal from each single vertex position
  37958. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37959. }
  37960. // Vertex normal need correction due to X,Y,Z radius scaling
  37961. vertex_normal.x /= radiusX;
  37962. vertex_normal.y /= radiusY;
  37963. vertex_normal.z /= radiusZ;
  37964. vertex_normal.normalize();
  37965. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37966. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37967. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37968. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37969. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37970. uvs.push(uv_interp.x, uv_interp.y);
  37971. // push each vertex has member of a face
  37972. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37973. indices.push(current_indice);
  37974. current_indice++;
  37975. };
  37976. for (var i2 = 0; i2 < subdivisions; i2++) {
  37977. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37978. // face : (i1,i2) for /\ :
  37979. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37980. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37981. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37982. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37983. if (i1 + i2 + 1 < subdivisions) {
  37984. // face : (i1,i2)' for \/ :
  37985. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37986. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37987. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37988. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37989. }
  37990. }
  37991. }
  37992. }
  37993. // Sides
  37994. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37995. // Result
  37996. var vertexData = new VertexData();
  37997. vertexData.indices = indices;
  37998. vertexData.positions = positions;
  37999. vertexData.normals = normals;
  38000. vertexData.uvs = uvs;
  38001. return vertexData;
  38002. };
  38003. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38004. /**
  38005. * Creates the VertexData for a Polyhedron
  38006. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38007. * * type provided types are:
  38008. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38009. * * 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)
  38010. * * size the size of the IcoSphere, optional default 1
  38011. * * sizeX allows stretching in the x direction, optional, default size
  38012. * * sizeY allows stretching in the y direction, optional, default size
  38013. * * sizeZ allows stretching in the z direction, optional, default size
  38014. * * 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
  38015. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38016. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38017. * * flat when true creates a flat shaded mesh, optional, default true
  38018. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38019. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38020. * * 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)
  38021. * * 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)
  38022. * @returns the VertexData of the Polyhedron
  38023. */
  38024. VertexData.CreatePolyhedron = function (options) {
  38025. // provided polyhedron types :
  38026. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38027. // 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)
  38028. var polyhedra = [];
  38029. 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]] };
  38030. 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]] };
  38031. polyhedra[2] = {
  38032. 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]],
  38033. 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]]
  38034. };
  38035. polyhedra[3] = {
  38036. 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]],
  38037. 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]]
  38038. };
  38039. polyhedra[4] = {
  38040. 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]],
  38041. 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]]
  38042. };
  38043. 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]] };
  38044. 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]] };
  38045. 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]] };
  38046. 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]] };
  38047. 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]] };
  38048. 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]] };
  38049. 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]] };
  38050. 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]] };
  38051. 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]] };
  38052. polyhedra[14] = {
  38053. 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]],
  38054. 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]]
  38055. };
  38056. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38057. var size = options.size;
  38058. var sizeX = options.sizeX || size || 1;
  38059. var sizeY = options.sizeY || size || 1;
  38060. var sizeZ = options.sizeZ || size || 1;
  38061. var data = options.custom || polyhedra[type];
  38062. var nbfaces = data.face.length;
  38063. var faceUV = options.faceUV || new Array(nbfaces);
  38064. var faceColors = options.faceColors;
  38065. var flat = (options.flat === undefined) ? true : options.flat;
  38066. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38067. var positions = new Array();
  38068. var indices = new Array();
  38069. var normals = new Array();
  38070. var uvs = new Array();
  38071. var colors = new Array();
  38072. var index = 0;
  38073. var faceIdx = 0; // face cursor in the array "indexes"
  38074. var indexes = new Array();
  38075. var i = 0;
  38076. var f = 0;
  38077. var u, v, ang, x, y, tmp;
  38078. // default face colors and UV if undefined
  38079. if (flat) {
  38080. for (f = 0; f < nbfaces; f++) {
  38081. if (faceColors && faceColors[f] === undefined) {
  38082. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38083. }
  38084. if (faceUV && faceUV[f] === undefined) {
  38085. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38086. }
  38087. }
  38088. }
  38089. if (!flat) {
  38090. for (i = 0; i < data.vertex.length; i++) {
  38091. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38092. uvs.push(0, 0);
  38093. }
  38094. for (f = 0; f < nbfaces; f++) {
  38095. for (i = 0; i < data.face[f].length - 2; i++) {
  38096. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38097. }
  38098. }
  38099. }
  38100. else {
  38101. for (f = 0; f < nbfaces; f++) {
  38102. var fl = data.face[f].length; // number of vertices of the current face
  38103. ang = 2 * Math.PI / fl;
  38104. x = 0.5 * Math.tan(ang / 2);
  38105. y = 0.5;
  38106. // positions, uvs, colors
  38107. for (i = 0; i < fl; i++) {
  38108. // positions
  38109. 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);
  38110. indexes.push(index);
  38111. index++;
  38112. // uvs
  38113. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38114. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38115. uvs.push(u, v);
  38116. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38117. y = x * Math.sin(ang) + y * Math.cos(ang);
  38118. x = tmp;
  38119. // colors
  38120. if (faceColors) {
  38121. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38122. }
  38123. }
  38124. // indices from indexes
  38125. for (i = 0; i < fl - 2; i++) {
  38126. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38127. }
  38128. faceIdx += fl;
  38129. }
  38130. }
  38131. VertexData.ComputeNormals(positions, indices, normals);
  38132. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38133. var vertexData = new VertexData();
  38134. vertexData.positions = positions;
  38135. vertexData.indices = indices;
  38136. vertexData.normals = normals;
  38137. vertexData.uvs = uvs;
  38138. if (faceColors && flat) {
  38139. vertexData.colors = colors;
  38140. }
  38141. return vertexData;
  38142. };
  38143. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38144. /**
  38145. * Creates the VertexData for a TorusKnot
  38146. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38147. * * radius the radius of the torus knot, optional, default 2
  38148. * * tube the thickness of the tube, optional, default 0.5
  38149. * * radialSegments the number of sides on each tube segments, optional, default 32
  38150. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38151. * * p the number of windings around the z axis, optional, default 2
  38152. * * q the number of windings around the x axis, optional, default 3
  38153. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38154. * * 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)
  38155. * * 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)
  38156. * @returns the VertexData of the Torus Knot
  38157. */
  38158. VertexData.CreateTorusKnot = function (options) {
  38159. var indices = new Array();
  38160. var positions = new Array();
  38161. var normals = new Array();
  38162. var uvs = new Array();
  38163. var radius = options.radius || 2;
  38164. var tube = options.tube || 0.5;
  38165. var radialSegments = options.radialSegments || 32;
  38166. var tubularSegments = options.tubularSegments || 32;
  38167. var p = options.p || 2;
  38168. var q = options.q || 3;
  38169. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38170. // Helper
  38171. var getPos = function (angle) {
  38172. var cu = Math.cos(angle);
  38173. var su = Math.sin(angle);
  38174. var quOverP = q / p * angle;
  38175. var cs = Math.cos(quOverP);
  38176. var tx = radius * (2 + cs) * 0.5 * cu;
  38177. var ty = radius * (2 + cs) * su * 0.5;
  38178. var tz = radius * Math.sin(quOverP) * 0.5;
  38179. return new BABYLON.Vector3(tx, ty, tz);
  38180. };
  38181. // Vertices
  38182. var i;
  38183. var j;
  38184. for (i = 0; i <= radialSegments; i++) {
  38185. var modI = i % radialSegments;
  38186. var u = modI / radialSegments * 2 * p * Math.PI;
  38187. var p1 = getPos(u);
  38188. var p2 = getPos(u + 0.01);
  38189. var tang = p2.subtract(p1);
  38190. var n = p2.add(p1);
  38191. var bitan = BABYLON.Vector3.Cross(tang, n);
  38192. n = BABYLON.Vector3.Cross(bitan, tang);
  38193. bitan.normalize();
  38194. n.normalize();
  38195. for (j = 0; j < tubularSegments; j++) {
  38196. var modJ = j % tubularSegments;
  38197. var v = modJ / tubularSegments * 2 * Math.PI;
  38198. var cx = -tube * Math.cos(v);
  38199. var cy = tube * Math.sin(v);
  38200. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38201. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38202. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38203. uvs.push(i / radialSegments);
  38204. uvs.push(j / tubularSegments);
  38205. }
  38206. }
  38207. for (i = 0; i < radialSegments; i++) {
  38208. for (j = 0; j < tubularSegments; j++) {
  38209. var jNext = (j + 1) % tubularSegments;
  38210. var a = i * tubularSegments + j;
  38211. var b = (i + 1) * tubularSegments + j;
  38212. var c = (i + 1) * tubularSegments + jNext;
  38213. var d = i * tubularSegments + jNext;
  38214. indices.push(d);
  38215. indices.push(b);
  38216. indices.push(a);
  38217. indices.push(d);
  38218. indices.push(c);
  38219. indices.push(b);
  38220. }
  38221. }
  38222. // Normals
  38223. VertexData.ComputeNormals(positions, indices, normals);
  38224. // Sides
  38225. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38226. // Result
  38227. var vertexData = new VertexData();
  38228. vertexData.indices = indices;
  38229. vertexData.positions = positions;
  38230. vertexData.normals = normals;
  38231. vertexData.uvs = uvs;
  38232. return vertexData;
  38233. };
  38234. // Tools
  38235. /**
  38236. * Compute normals for given positions and indices
  38237. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38238. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38239. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38240. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38241. * * facetNormals : optional array of facet normals (vector3)
  38242. * * facetPositions : optional array of facet positions (vector3)
  38243. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38244. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38245. * * bInfo : optional bounding info, required for facetPartitioning computation
  38246. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38247. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38248. * * useRightHandedSystem: optional boolean to for right handed system computation
  38249. * * depthSort : optional boolean to enable the facet depth sort computation
  38250. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38251. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38252. */
  38253. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38254. // temporary scalar variables
  38255. var index = 0; // facet index
  38256. var p1p2x = 0.0; // p1p2 vector x coordinate
  38257. var p1p2y = 0.0; // p1p2 vector y coordinate
  38258. var p1p2z = 0.0; // p1p2 vector z coordinate
  38259. var p3p2x = 0.0; // p3p2 vector x coordinate
  38260. var p3p2y = 0.0; // p3p2 vector y coordinate
  38261. var p3p2z = 0.0; // p3p2 vector z coordinate
  38262. var faceNormalx = 0.0; // facet normal x coordinate
  38263. var faceNormaly = 0.0; // facet normal y coordinate
  38264. var faceNormalz = 0.0; // facet normal z coordinate
  38265. var length = 0.0; // facet normal length before normalization
  38266. var v1x = 0; // vector1 x index in the positions array
  38267. var v1y = 0; // vector1 y index in the positions array
  38268. var v1z = 0; // vector1 z index in the positions array
  38269. var v2x = 0; // vector2 x index in the positions array
  38270. var v2y = 0; // vector2 y index in the positions array
  38271. var v2z = 0; // vector2 z index in the positions array
  38272. var v3x = 0; // vector3 x index in the positions array
  38273. var v3y = 0; // vector3 y index in the positions array
  38274. var v3z = 0; // vector3 z index in the positions array
  38275. var computeFacetNormals = false;
  38276. var computeFacetPositions = false;
  38277. var computeFacetPartitioning = false;
  38278. var computeDepthSort = false;
  38279. var faceNormalSign = 1;
  38280. var ratio = 0;
  38281. var distanceTo = null;
  38282. if (options) {
  38283. computeFacetNormals = (options.facetNormals) ? true : false;
  38284. computeFacetPositions = (options.facetPositions) ? true : false;
  38285. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38286. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38287. ratio = options.ratio || 0;
  38288. computeDepthSort = (options.depthSort) ? true : false;
  38289. distanceTo = (options.distanceTo);
  38290. if (computeDepthSort) {
  38291. if (distanceTo === undefined) {
  38292. distanceTo = BABYLON.Vector3.Zero();
  38293. }
  38294. var depthSortedFacets = options.depthSortedFacets;
  38295. }
  38296. }
  38297. // facetPartitioning reinit if needed
  38298. var xSubRatio = 0;
  38299. var ySubRatio = 0;
  38300. var zSubRatio = 0;
  38301. var subSq = 0;
  38302. if (computeFacetPartitioning && options && options.bbSize) {
  38303. var ox = 0; // X partitioning index for facet position
  38304. var oy = 0; // Y partinioning index for facet position
  38305. var oz = 0; // Z partinioning index for facet position
  38306. var b1x = 0; // X partitioning index for facet v1 vertex
  38307. var b1y = 0; // Y partitioning index for facet v1 vertex
  38308. var b1z = 0; // z partitioning index for facet v1 vertex
  38309. var b2x = 0; // X partitioning index for facet v2 vertex
  38310. var b2y = 0; // Y partitioning index for facet v2 vertex
  38311. var b2z = 0; // Z partitioning index for facet v2 vertex
  38312. var b3x = 0; // X partitioning index for facet v3 vertex
  38313. var b3y = 0; // Y partitioning index for facet v3 vertex
  38314. var b3z = 0; // Z partitioning index for facet v3 vertex
  38315. var block_idx_o = 0; // facet barycenter block index
  38316. var block_idx_v1 = 0; // v1 vertex block index
  38317. var block_idx_v2 = 0; // v2 vertex block index
  38318. var block_idx_v3 = 0; // v3 vertex block index
  38319. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38320. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38321. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38322. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38323. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38324. subSq = options.subDiv.max * options.subDiv.max;
  38325. options.facetPartitioning.length = 0;
  38326. }
  38327. // reset the normals
  38328. for (index = 0; index < positions.length; index++) {
  38329. normals[index] = 0.0;
  38330. }
  38331. // Loop : 1 indice triplet = 1 facet
  38332. var nbFaces = (indices.length / 3) | 0;
  38333. for (index = 0; index < nbFaces; index++) {
  38334. // get the indexes of the coordinates of each vertex of the facet
  38335. v1x = indices[index * 3] * 3;
  38336. v1y = v1x + 1;
  38337. v1z = v1x + 2;
  38338. v2x = indices[index * 3 + 1] * 3;
  38339. v2y = v2x + 1;
  38340. v2z = v2x + 2;
  38341. v3x = indices[index * 3 + 2] * 3;
  38342. v3y = v3x + 1;
  38343. v3z = v3x + 2;
  38344. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38345. p1p2y = positions[v1y] - positions[v2y];
  38346. p1p2z = positions[v1z] - positions[v2z];
  38347. p3p2x = positions[v3x] - positions[v2x];
  38348. p3p2y = positions[v3y] - positions[v2y];
  38349. p3p2z = positions[v3z] - positions[v2z];
  38350. // compute the face normal with the cross product
  38351. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38352. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38353. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38354. // normalize this normal and store it in the array facetData
  38355. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38356. length = (length === 0) ? 1.0 : length;
  38357. faceNormalx /= length;
  38358. faceNormaly /= length;
  38359. faceNormalz /= length;
  38360. if (computeFacetNormals && options) {
  38361. options.facetNormals[index].x = faceNormalx;
  38362. options.facetNormals[index].y = faceNormaly;
  38363. options.facetNormals[index].z = faceNormalz;
  38364. }
  38365. if (computeFacetPositions && options) {
  38366. // compute and the facet barycenter coordinates in the array facetPositions
  38367. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38368. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38369. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38370. }
  38371. if (computeFacetPartitioning && options) {
  38372. // store the facet indexes in arrays in the main facetPartitioning array :
  38373. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38374. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38375. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38376. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38377. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38378. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38379. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38380. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38381. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38382. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38383. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38384. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38385. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38386. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38387. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38388. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38389. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38390. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38391. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38392. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38393. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38394. // push each facet index in each block containing the vertex
  38395. options.facetPartitioning[block_idx_v1].push(index);
  38396. if (block_idx_v2 != block_idx_v1) {
  38397. options.facetPartitioning[block_idx_v2].push(index);
  38398. }
  38399. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38400. options.facetPartitioning[block_idx_v3].push(index);
  38401. }
  38402. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38403. options.facetPartitioning[block_idx_o].push(index);
  38404. }
  38405. }
  38406. if (computeDepthSort && options && options.facetPositions) {
  38407. var dsf = depthSortedFacets[index];
  38408. dsf.ind = index * 3;
  38409. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38410. }
  38411. // compute the normals anyway
  38412. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38413. normals[v1y] += faceNormaly;
  38414. normals[v1z] += faceNormalz;
  38415. normals[v2x] += faceNormalx;
  38416. normals[v2y] += faceNormaly;
  38417. normals[v2z] += faceNormalz;
  38418. normals[v3x] += faceNormalx;
  38419. normals[v3y] += faceNormaly;
  38420. normals[v3z] += faceNormalz;
  38421. }
  38422. // last normalization of each normal
  38423. for (index = 0; index < normals.length / 3; index++) {
  38424. faceNormalx = normals[index * 3];
  38425. faceNormaly = normals[index * 3 + 1];
  38426. faceNormalz = normals[index * 3 + 2];
  38427. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38428. length = (length === 0) ? 1.0 : length;
  38429. faceNormalx /= length;
  38430. faceNormaly /= length;
  38431. faceNormalz /= length;
  38432. normals[index * 3] = faceNormalx;
  38433. normals[index * 3 + 1] = faceNormaly;
  38434. normals[index * 3 + 2] = faceNormalz;
  38435. }
  38436. };
  38437. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38438. var li = indices.length;
  38439. var ln = normals.length;
  38440. var i;
  38441. var n;
  38442. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38443. switch (sideOrientation) {
  38444. case BABYLON.Mesh.FRONTSIDE:
  38445. // nothing changed
  38446. break;
  38447. case BABYLON.Mesh.BACKSIDE:
  38448. var tmp;
  38449. // indices
  38450. for (i = 0; i < li; i += 3) {
  38451. tmp = indices[i];
  38452. indices[i] = indices[i + 2];
  38453. indices[i + 2] = tmp;
  38454. }
  38455. // normals
  38456. for (n = 0; n < ln; n++) {
  38457. normals[n] = -normals[n];
  38458. }
  38459. break;
  38460. case BABYLON.Mesh.DOUBLESIDE:
  38461. // positions
  38462. var lp = positions.length;
  38463. var l = lp / 3;
  38464. for (var p = 0; p < lp; p++) {
  38465. positions[lp + p] = positions[p];
  38466. }
  38467. // indices
  38468. for (i = 0; i < li; i += 3) {
  38469. indices[i + li] = indices[i + 2] + l;
  38470. indices[i + 1 + li] = indices[i + 1] + l;
  38471. indices[i + 2 + li] = indices[i] + l;
  38472. }
  38473. // normals
  38474. for (n = 0; n < ln; n++) {
  38475. normals[ln + n] = -normals[n];
  38476. }
  38477. // uvs
  38478. var lu = uvs.length;
  38479. var u = 0;
  38480. for (u = 0; u < lu; u++) {
  38481. uvs[u + lu] = uvs[u];
  38482. }
  38483. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38484. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38485. u = 0;
  38486. for (i = 0; i < lu / 2; i++) {
  38487. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38488. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38489. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38490. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38491. u += 2;
  38492. }
  38493. break;
  38494. }
  38495. };
  38496. /**
  38497. * Applies VertexData created from the imported parameters to the geometry
  38498. * @param parsedVertexData the parsed data from an imported file
  38499. * @param geometry the geometry to apply the VertexData to
  38500. */
  38501. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38502. var vertexData = new VertexData();
  38503. // positions
  38504. var positions = parsedVertexData.positions;
  38505. if (positions) {
  38506. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38507. }
  38508. // normals
  38509. var normals = parsedVertexData.normals;
  38510. if (normals) {
  38511. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38512. }
  38513. // tangents
  38514. var tangents = parsedVertexData.tangents;
  38515. if (tangents) {
  38516. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38517. }
  38518. // uvs
  38519. var uvs = parsedVertexData.uvs;
  38520. if (uvs) {
  38521. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38522. }
  38523. // uv2s
  38524. var uv2s = parsedVertexData.uv2s;
  38525. if (uv2s) {
  38526. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38527. }
  38528. // uv3s
  38529. var uv3s = parsedVertexData.uv3s;
  38530. if (uv3s) {
  38531. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38532. }
  38533. // uv4s
  38534. var uv4s = parsedVertexData.uv4s;
  38535. if (uv4s) {
  38536. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38537. }
  38538. // uv5s
  38539. var uv5s = parsedVertexData.uv5s;
  38540. if (uv5s) {
  38541. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38542. }
  38543. // uv6s
  38544. var uv6s = parsedVertexData.uv6s;
  38545. if (uv6s) {
  38546. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38547. }
  38548. // colors
  38549. var colors = parsedVertexData.colors;
  38550. if (colors) {
  38551. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38552. }
  38553. // matricesIndices
  38554. var matricesIndices = parsedVertexData.matricesIndices;
  38555. if (matricesIndices) {
  38556. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38557. }
  38558. // matricesWeights
  38559. var matricesWeights = parsedVertexData.matricesWeights;
  38560. if (matricesWeights) {
  38561. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38562. }
  38563. // indices
  38564. var indices = parsedVertexData.indices;
  38565. if (indices) {
  38566. vertexData.indices = indices;
  38567. }
  38568. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38569. };
  38570. return VertexData;
  38571. }());
  38572. BABYLON.VertexData = VertexData;
  38573. })(BABYLON || (BABYLON = {}));
  38574. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38575. var BABYLON;
  38576. (function (BABYLON) {
  38577. /**
  38578. * Class used to store geometry data (vertex buffers + index buffer)
  38579. */
  38580. var Geometry = /** @class */ (function () {
  38581. /**
  38582. * Creates a new geometry
  38583. * @param id defines the unique ID
  38584. * @param scene defines the hosting scene
  38585. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38586. * @param updatable defines if geometry must be updatable (false by default)
  38587. * @param mesh defines the mesh that will be associated with the geometry
  38588. */
  38589. function Geometry(id, scene, vertexData, updatable, mesh) {
  38590. if (updatable === void 0) { updatable = false; }
  38591. if (mesh === void 0) { mesh = null; }
  38592. /**
  38593. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38594. */
  38595. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38596. this._totalVertices = 0;
  38597. this._isDisposed = false;
  38598. this._indexBufferIsUpdatable = false;
  38599. this.id = id;
  38600. this._engine = scene.getEngine();
  38601. this._meshes = [];
  38602. this._scene = scene;
  38603. //Init vertex buffer cache
  38604. this._vertexBuffers = {};
  38605. this._indices = [];
  38606. this._updatable = updatable;
  38607. // vertexData
  38608. if (vertexData) {
  38609. this.setAllVerticesData(vertexData, updatable);
  38610. }
  38611. else {
  38612. this._totalVertices = 0;
  38613. this._indices = [];
  38614. }
  38615. if (this._engine.getCaps().vertexArrayObject) {
  38616. this._vertexArrayObjects = {};
  38617. }
  38618. // applyToMesh
  38619. if (mesh) {
  38620. if (mesh.getClassName() === "LinesMesh") {
  38621. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38622. this._updateExtend();
  38623. }
  38624. this.applyToMesh(mesh);
  38625. mesh.computeWorldMatrix(true);
  38626. }
  38627. }
  38628. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38629. /**
  38630. * 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
  38631. */
  38632. get: function () {
  38633. return this._boundingBias;
  38634. },
  38635. /**
  38636. * 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
  38637. */
  38638. set: function (value) {
  38639. if (this._boundingBias && this._boundingBias.equals(value)) {
  38640. return;
  38641. }
  38642. this._boundingBias = value.clone();
  38643. this._updateBoundingInfo(true, null);
  38644. },
  38645. enumerable: true,
  38646. configurable: true
  38647. });
  38648. /**
  38649. * Static function used to attach a new empty geometry to a mesh
  38650. * @param mesh defines the mesh to attach the geometry to
  38651. * @returns the new {BABYLON.Geometry}
  38652. */
  38653. Geometry.CreateGeometryForMesh = function (mesh) {
  38654. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38655. geometry.applyToMesh(mesh);
  38656. return geometry;
  38657. };
  38658. Object.defineProperty(Geometry.prototype, "extend", {
  38659. /**
  38660. * Gets the current extend of the geometry
  38661. */
  38662. get: function () {
  38663. return this._extend;
  38664. },
  38665. enumerable: true,
  38666. configurable: true
  38667. });
  38668. /**
  38669. * Gets the hosting scene
  38670. * @returns the hosting {BABYLON.Scene}
  38671. */
  38672. Geometry.prototype.getScene = function () {
  38673. return this._scene;
  38674. };
  38675. /**
  38676. * Gets the hosting engine
  38677. * @returns the hosting {BABYLON.Engine}
  38678. */
  38679. Geometry.prototype.getEngine = function () {
  38680. return this._engine;
  38681. };
  38682. /**
  38683. * Defines if the geometry is ready to use
  38684. * @returns true if the geometry is ready to be used
  38685. */
  38686. Geometry.prototype.isReady = function () {
  38687. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38688. };
  38689. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38690. /**
  38691. * Gets a value indicating that the geometry should not be serialized
  38692. */
  38693. get: function () {
  38694. for (var index = 0; index < this._meshes.length; index++) {
  38695. if (!this._meshes[index].doNotSerialize) {
  38696. return false;
  38697. }
  38698. }
  38699. return true;
  38700. },
  38701. enumerable: true,
  38702. configurable: true
  38703. });
  38704. /** @hidden */
  38705. Geometry.prototype._rebuild = function () {
  38706. if (this._vertexArrayObjects) {
  38707. this._vertexArrayObjects = {};
  38708. }
  38709. // Index buffer
  38710. if (this._meshes.length !== 0 && this._indices) {
  38711. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38712. }
  38713. // Vertex buffers
  38714. for (var key in this._vertexBuffers) {
  38715. var vertexBuffer = this._vertexBuffers[key];
  38716. vertexBuffer._rebuild();
  38717. }
  38718. };
  38719. /**
  38720. * Affects all gemetry data in one call
  38721. * @param vertexData defines the geometry data
  38722. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38723. */
  38724. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38725. vertexData.applyToGeometry(this, updatable);
  38726. this.notifyUpdate();
  38727. };
  38728. /**
  38729. * Set specific vertex data
  38730. * @param kind defines the data kind (Position, normal, etc...)
  38731. * @param data defines the vertex data to use
  38732. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38733. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38734. */
  38735. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38736. if (updatable === void 0) { updatable = false; }
  38737. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38738. this.setVerticesBuffer(buffer);
  38739. };
  38740. /**
  38741. * Removes a specific vertex data
  38742. * @param kind defines the data kind (Position, normal, etc...)
  38743. */
  38744. Geometry.prototype.removeVerticesData = function (kind) {
  38745. if (this._vertexBuffers[kind]) {
  38746. this._vertexBuffers[kind].dispose();
  38747. delete this._vertexBuffers[kind];
  38748. }
  38749. };
  38750. /**
  38751. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38752. * @param buffer defines the vertex buffer to use
  38753. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38754. */
  38755. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38756. if (totalVertices === void 0) { totalVertices = null; }
  38757. var kind = buffer.getKind();
  38758. if (this._vertexBuffers[kind]) {
  38759. this._vertexBuffers[kind].dispose();
  38760. }
  38761. this._vertexBuffers[kind] = buffer;
  38762. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38763. var data = buffer.getData();
  38764. if (totalVertices != null) {
  38765. this._totalVertices = totalVertices;
  38766. }
  38767. else {
  38768. if (data != null) {
  38769. this._totalVertices = data.length / (buffer.byteStride / 4);
  38770. }
  38771. }
  38772. this._updateExtend(data);
  38773. this._resetPointsArrayCache();
  38774. var meshes = this._meshes;
  38775. var numOfMeshes = meshes.length;
  38776. for (var index = 0; index < numOfMeshes; index++) {
  38777. var mesh = meshes[index];
  38778. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38779. mesh._createGlobalSubMesh(false);
  38780. mesh.computeWorldMatrix(true);
  38781. }
  38782. }
  38783. this.notifyUpdate(kind);
  38784. if (this._vertexArrayObjects) {
  38785. this._disposeVertexArrayObjects();
  38786. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38787. }
  38788. };
  38789. /**
  38790. * Update a specific vertex buffer
  38791. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38792. * It will do nothing if the buffer is not updatable
  38793. * @param kind defines the data kind (Position, normal, etc...)
  38794. * @param data defines the data to use
  38795. * @param offset defines the offset in the target buffer where to store the data
  38796. * @param useBytes set to true if the offset is in bytes
  38797. */
  38798. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38799. if (useBytes === void 0) { useBytes = false; }
  38800. var vertexBuffer = this.getVertexBuffer(kind);
  38801. if (!vertexBuffer) {
  38802. return;
  38803. }
  38804. vertexBuffer.updateDirectly(data, offset, useBytes);
  38805. this.notifyUpdate(kind);
  38806. };
  38807. /**
  38808. * Update a specific vertex buffer
  38809. * This function will create a new buffer if the current one is not updatable
  38810. * @param kind defines the data kind (Position, normal, etc...)
  38811. * @param data defines the data to use
  38812. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38813. */
  38814. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38815. if (updateExtends === void 0) { updateExtends = false; }
  38816. var vertexBuffer = this.getVertexBuffer(kind);
  38817. if (!vertexBuffer) {
  38818. return;
  38819. }
  38820. vertexBuffer.update(data);
  38821. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38822. this._updateBoundingInfo(updateExtends, data);
  38823. }
  38824. this.notifyUpdate(kind);
  38825. };
  38826. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38827. if (updateExtends) {
  38828. this._updateExtend(data);
  38829. }
  38830. var meshes = this._meshes;
  38831. var numOfMeshes = meshes.length;
  38832. this._resetPointsArrayCache();
  38833. for (var index = 0; index < numOfMeshes; index++) {
  38834. var mesh = meshes[index];
  38835. if (updateExtends) {
  38836. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38837. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38838. var subMesh = mesh.subMeshes[subIndex];
  38839. subMesh.refreshBoundingInfo();
  38840. }
  38841. }
  38842. }
  38843. };
  38844. /** @hidden */
  38845. Geometry.prototype._bind = function (effect, indexToBind) {
  38846. if (!effect) {
  38847. return;
  38848. }
  38849. if (indexToBind === undefined) {
  38850. indexToBind = this._indexBuffer;
  38851. }
  38852. var vbs = this.getVertexBuffers();
  38853. if (!vbs) {
  38854. return;
  38855. }
  38856. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38857. this._engine.bindBuffers(vbs, indexToBind, effect);
  38858. return;
  38859. }
  38860. // Using VAO
  38861. if (!this._vertexArrayObjects[effect.key]) {
  38862. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38863. }
  38864. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38865. };
  38866. /**
  38867. * Gets total number of vertices
  38868. * @returns the total number of vertices
  38869. */
  38870. Geometry.prototype.getTotalVertices = function () {
  38871. if (!this.isReady()) {
  38872. return 0;
  38873. }
  38874. return this._totalVertices;
  38875. };
  38876. /**
  38877. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38878. * @param kind defines the data kind (Position, normal, etc...)
  38879. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38880. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38881. * @returns a float array containing vertex data
  38882. */
  38883. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38884. var vertexBuffer = this.getVertexBuffer(kind);
  38885. if (!vertexBuffer) {
  38886. return null;
  38887. }
  38888. var data = vertexBuffer.getData();
  38889. if (!data) {
  38890. return null;
  38891. }
  38892. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38893. var count = this._totalVertices * vertexBuffer.getSize();
  38894. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38895. var copy_1 = new Array(count);
  38896. vertexBuffer.forEach(count, function (value, index) {
  38897. copy_1[index] = value;
  38898. });
  38899. return copy_1;
  38900. }
  38901. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38902. if (data instanceof Array) {
  38903. var offset = vertexBuffer.byteOffset / 4;
  38904. return BABYLON.Tools.Slice(data, offset, offset + count);
  38905. }
  38906. else if (data instanceof ArrayBuffer) {
  38907. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38908. }
  38909. else {
  38910. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38911. }
  38912. }
  38913. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38914. return BABYLON.Tools.Slice(data);
  38915. }
  38916. return data;
  38917. };
  38918. /**
  38919. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38920. * @param kind defines the data kind (Position, normal, etc...)
  38921. * @returns true if the vertex buffer with the specified kind is updatable
  38922. */
  38923. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38924. var vb = this._vertexBuffers[kind];
  38925. if (!vb) {
  38926. return false;
  38927. }
  38928. return vb.isUpdatable();
  38929. };
  38930. /**
  38931. * Gets a specific vertex buffer
  38932. * @param kind defines the data kind (Position, normal, etc...)
  38933. * @returns a {BABYLON.VertexBuffer}
  38934. */
  38935. Geometry.prototype.getVertexBuffer = function (kind) {
  38936. if (!this.isReady()) {
  38937. return null;
  38938. }
  38939. return this._vertexBuffers[kind];
  38940. };
  38941. /**
  38942. * Returns all vertex buffers
  38943. * @return an object holding all vertex buffers indexed by kind
  38944. */
  38945. Geometry.prototype.getVertexBuffers = function () {
  38946. if (!this.isReady()) {
  38947. return null;
  38948. }
  38949. return this._vertexBuffers;
  38950. };
  38951. /**
  38952. * Gets a boolean indicating if specific vertex buffer is present
  38953. * @param kind defines the data kind (Position, normal, etc...)
  38954. * @returns true if data is present
  38955. */
  38956. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38957. if (!this._vertexBuffers) {
  38958. if (this._delayInfo) {
  38959. return this._delayInfo.indexOf(kind) !== -1;
  38960. }
  38961. return false;
  38962. }
  38963. return this._vertexBuffers[kind] !== undefined;
  38964. };
  38965. /**
  38966. * Gets a list of all attached data kinds (Position, normal, etc...)
  38967. * @returns a list of string containing all kinds
  38968. */
  38969. Geometry.prototype.getVerticesDataKinds = function () {
  38970. var result = [];
  38971. var kind;
  38972. if (!this._vertexBuffers && this._delayInfo) {
  38973. for (kind in this._delayInfo) {
  38974. result.push(kind);
  38975. }
  38976. }
  38977. else {
  38978. for (kind in this._vertexBuffers) {
  38979. result.push(kind);
  38980. }
  38981. }
  38982. return result;
  38983. };
  38984. /**
  38985. * Update index buffer
  38986. * @param indices defines the indices to store in the index buffer
  38987. * @param offset defines the offset in the target buffer where to store the data
  38988. */
  38989. Geometry.prototype.updateIndices = function (indices, offset) {
  38990. if (!this._indexBuffer) {
  38991. return;
  38992. }
  38993. if (!this._indexBufferIsUpdatable) {
  38994. this.setIndices(indices, null, true);
  38995. }
  38996. else {
  38997. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38998. }
  38999. };
  39000. /**
  39001. * Creates a new index buffer
  39002. * @param indices defines the indices to store in the index buffer
  39003. * @param totalVertices defines the total number of vertices (could be null)
  39004. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39005. */
  39006. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39007. if (totalVertices === void 0) { totalVertices = null; }
  39008. if (updatable === void 0) { updatable = false; }
  39009. if (this._indexBuffer) {
  39010. this._engine._releaseBuffer(this._indexBuffer);
  39011. }
  39012. this._disposeVertexArrayObjects();
  39013. this._indices = indices;
  39014. this._indexBufferIsUpdatable = updatable;
  39015. if (this._meshes.length !== 0 && this._indices) {
  39016. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39017. }
  39018. if (totalVertices != undefined) { // including null and undefined
  39019. this._totalVertices = totalVertices;
  39020. }
  39021. var meshes = this._meshes;
  39022. var numOfMeshes = meshes.length;
  39023. for (var index = 0; index < numOfMeshes; index++) {
  39024. meshes[index]._createGlobalSubMesh(true);
  39025. }
  39026. this.notifyUpdate();
  39027. };
  39028. /**
  39029. * Return the total number of indices
  39030. * @returns the total number of indices
  39031. */
  39032. Geometry.prototype.getTotalIndices = function () {
  39033. if (!this.isReady()) {
  39034. return 0;
  39035. }
  39036. return this._indices.length;
  39037. };
  39038. /**
  39039. * Gets the index buffer array
  39040. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39041. * @returns the index buffer array
  39042. */
  39043. Geometry.prototype.getIndices = function (copyWhenShared) {
  39044. if (!this.isReady()) {
  39045. return null;
  39046. }
  39047. var orig = this._indices;
  39048. if (!copyWhenShared || this._meshes.length === 1) {
  39049. return orig;
  39050. }
  39051. else {
  39052. var len = orig.length;
  39053. var copy = [];
  39054. for (var i = 0; i < len; i++) {
  39055. copy.push(orig[i]);
  39056. }
  39057. return copy;
  39058. }
  39059. };
  39060. /**
  39061. * Gets the index buffer
  39062. * @return the index buffer
  39063. */
  39064. Geometry.prototype.getIndexBuffer = function () {
  39065. if (!this.isReady()) {
  39066. return null;
  39067. }
  39068. return this._indexBuffer;
  39069. };
  39070. /** @hidden */
  39071. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39072. if (effect === void 0) { effect = null; }
  39073. if (!effect || !this._vertexArrayObjects) {
  39074. return;
  39075. }
  39076. if (this._vertexArrayObjects[effect.key]) {
  39077. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39078. delete this._vertexArrayObjects[effect.key];
  39079. }
  39080. };
  39081. /**
  39082. * Release the associated resources for a specific mesh
  39083. * @param mesh defines the source mesh
  39084. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39085. */
  39086. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39087. var meshes = this._meshes;
  39088. var index = meshes.indexOf(mesh);
  39089. if (index === -1) {
  39090. return;
  39091. }
  39092. meshes.splice(index, 1);
  39093. mesh._geometry = null;
  39094. if (meshes.length === 0 && shouldDispose) {
  39095. this.dispose();
  39096. }
  39097. };
  39098. /**
  39099. * Apply current geometry to a given mesh
  39100. * @param mesh defines the mesh to apply geometry to
  39101. */
  39102. Geometry.prototype.applyToMesh = function (mesh) {
  39103. if (mesh._geometry === this) {
  39104. return;
  39105. }
  39106. var previousGeometry = mesh._geometry;
  39107. if (previousGeometry) {
  39108. previousGeometry.releaseForMesh(mesh);
  39109. }
  39110. var meshes = this._meshes;
  39111. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39112. mesh._geometry = this;
  39113. this._scene.pushGeometry(this);
  39114. meshes.push(mesh);
  39115. if (this.isReady()) {
  39116. this._applyToMesh(mesh);
  39117. }
  39118. else {
  39119. mesh._boundingInfo = this._boundingInfo;
  39120. }
  39121. };
  39122. Geometry.prototype._updateExtend = function (data) {
  39123. if (data === void 0) { data = null; }
  39124. if (!data) {
  39125. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39126. }
  39127. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39128. };
  39129. Geometry.prototype._applyToMesh = function (mesh) {
  39130. var numOfMeshes = this._meshes.length;
  39131. // vertexBuffers
  39132. for (var kind in this._vertexBuffers) {
  39133. if (numOfMeshes === 1) {
  39134. this._vertexBuffers[kind].create();
  39135. }
  39136. var buffer = this._vertexBuffers[kind].getBuffer();
  39137. if (buffer)
  39138. buffer.references = numOfMeshes;
  39139. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39140. if (!this._extend) {
  39141. this._updateExtend();
  39142. }
  39143. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39144. mesh._createGlobalSubMesh(false);
  39145. //bounding info was just created again, world matrix should be applied again.
  39146. mesh._updateBoundingInfo();
  39147. }
  39148. }
  39149. // indexBuffer
  39150. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39151. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39152. }
  39153. if (this._indexBuffer) {
  39154. this._indexBuffer.references = numOfMeshes;
  39155. }
  39156. };
  39157. Geometry.prototype.notifyUpdate = function (kind) {
  39158. if (this.onGeometryUpdated) {
  39159. this.onGeometryUpdated(this, kind);
  39160. }
  39161. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39162. var mesh = _a[_i];
  39163. mesh._markSubMeshesAsAttributesDirty();
  39164. }
  39165. };
  39166. /**
  39167. * Load the geometry if it was flagged as delay loaded
  39168. * @param scene defines the hosting scene
  39169. * @param onLoaded defines a callback called when the geometry is loaded
  39170. */
  39171. Geometry.prototype.load = function (scene, onLoaded) {
  39172. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39173. return;
  39174. }
  39175. if (this.isReady()) {
  39176. if (onLoaded) {
  39177. onLoaded();
  39178. }
  39179. return;
  39180. }
  39181. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39182. this._queueLoad(scene, onLoaded);
  39183. };
  39184. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39185. var _this = this;
  39186. if (!this.delayLoadingFile) {
  39187. return;
  39188. }
  39189. scene._addPendingData(this);
  39190. scene._loadFile(this.delayLoadingFile, function (data) {
  39191. if (!_this._delayLoadingFunction) {
  39192. return;
  39193. }
  39194. _this._delayLoadingFunction(JSON.parse(data), _this);
  39195. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39196. _this._delayInfo = [];
  39197. scene._removePendingData(_this);
  39198. var meshes = _this._meshes;
  39199. var numOfMeshes = meshes.length;
  39200. for (var index = 0; index < numOfMeshes; index++) {
  39201. _this._applyToMesh(meshes[index]);
  39202. }
  39203. if (onLoaded) {
  39204. onLoaded();
  39205. }
  39206. }, undefined, true);
  39207. };
  39208. /**
  39209. * Invert the geometry to move from a right handed system to a left handed one.
  39210. */
  39211. Geometry.prototype.toLeftHanded = function () {
  39212. // Flip faces
  39213. var tIndices = this.getIndices(false);
  39214. if (tIndices != null && tIndices.length > 0) {
  39215. for (var i = 0; i < tIndices.length; i += 3) {
  39216. var tTemp = tIndices[i + 0];
  39217. tIndices[i + 0] = tIndices[i + 2];
  39218. tIndices[i + 2] = tTemp;
  39219. }
  39220. this.setIndices(tIndices);
  39221. }
  39222. // Negate position.z
  39223. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39224. if (tPositions != null && tPositions.length > 0) {
  39225. for (var i = 0; i < tPositions.length; i += 3) {
  39226. tPositions[i + 2] = -tPositions[i + 2];
  39227. }
  39228. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39229. }
  39230. // Negate normal.z
  39231. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39232. if (tNormals != null && tNormals.length > 0) {
  39233. for (var i = 0; i < tNormals.length; i += 3) {
  39234. tNormals[i + 2] = -tNormals[i + 2];
  39235. }
  39236. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39237. }
  39238. };
  39239. // Cache
  39240. /** @hidden */
  39241. Geometry.prototype._resetPointsArrayCache = function () {
  39242. this._positions = null;
  39243. };
  39244. /** @hidden */
  39245. Geometry.prototype._generatePointsArray = function () {
  39246. if (this._positions)
  39247. return true;
  39248. this._positions = [];
  39249. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39250. if (!data) {
  39251. return false;
  39252. }
  39253. for (var index = 0; index < data.length; index += 3) {
  39254. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39255. }
  39256. return true;
  39257. };
  39258. /**
  39259. * Gets a value indicating if the geometry is disposed
  39260. * @returns true if the geometry was disposed
  39261. */
  39262. Geometry.prototype.isDisposed = function () {
  39263. return this._isDisposed;
  39264. };
  39265. Geometry.prototype._disposeVertexArrayObjects = function () {
  39266. if (this._vertexArrayObjects) {
  39267. for (var kind in this._vertexArrayObjects) {
  39268. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39269. }
  39270. this._vertexArrayObjects = {};
  39271. }
  39272. };
  39273. /**
  39274. * Free all associated resources
  39275. */
  39276. Geometry.prototype.dispose = function () {
  39277. var meshes = this._meshes;
  39278. var numOfMeshes = meshes.length;
  39279. var index;
  39280. for (index = 0; index < numOfMeshes; index++) {
  39281. this.releaseForMesh(meshes[index]);
  39282. }
  39283. this._meshes = [];
  39284. this._disposeVertexArrayObjects();
  39285. for (var kind in this._vertexBuffers) {
  39286. this._vertexBuffers[kind].dispose();
  39287. }
  39288. this._vertexBuffers = {};
  39289. this._totalVertices = 0;
  39290. if (this._indexBuffer) {
  39291. this._engine._releaseBuffer(this._indexBuffer);
  39292. }
  39293. this._indexBuffer = null;
  39294. this._indices = [];
  39295. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39296. this.delayLoadingFile = null;
  39297. this._delayLoadingFunction = null;
  39298. this._delayInfo = [];
  39299. this._boundingInfo = null;
  39300. this._scene.removeGeometry(this);
  39301. this._isDisposed = true;
  39302. };
  39303. /**
  39304. * Clone the current geometry into a new geometry
  39305. * @param id defines the unique ID of the new geometry
  39306. * @returns a new geometry object
  39307. */
  39308. Geometry.prototype.copy = function (id) {
  39309. var vertexData = new BABYLON.VertexData();
  39310. vertexData.indices = [];
  39311. var indices = this.getIndices();
  39312. if (indices) {
  39313. for (var index = 0; index < indices.length; index++) {
  39314. vertexData.indices.push(indices[index]);
  39315. }
  39316. }
  39317. var updatable = false;
  39318. var stopChecking = false;
  39319. var kind;
  39320. for (kind in this._vertexBuffers) {
  39321. // using slice() to make a copy of the array and not just reference it
  39322. var data = this.getVerticesData(kind);
  39323. if (data instanceof Float32Array) {
  39324. vertexData.set(new Float32Array(data), kind);
  39325. }
  39326. else {
  39327. vertexData.set(data.slice(0), kind);
  39328. }
  39329. if (!stopChecking) {
  39330. var vb = this.getVertexBuffer(kind);
  39331. if (vb) {
  39332. updatable = vb.isUpdatable();
  39333. stopChecking = !updatable;
  39334. }
  39335. }
  39336. }
  39337. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39338. geometry.delayLoadState = this.delayLoadState;
  39339. geometry.delayLoadingFile = this.delayLoadingFile;
  39340. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39341. for (kind in this._delayInfo) {
  39342. geometry._delayInfo = geometry._delayInfo || [];
  39343. geometry._delayInfo.push(kind);
  39344. }
  39345. // Bounding info
  39346. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39347. return geometry;
  39348. };
  39349. /**
  39350. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39351. * @return a JSON representation of the current geometry data (without the vertices data)
  39352. */
  39353. Geometry.prototype.serialize = function () {
  39354. var serializationObject = {};
  39355. serializationObject.id = this.id;
  39356. serializationObject.updatable = this._updatable;
  39357. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39358. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39359. }
  39360. return serializationObject;
  39361. };
  39362. Geometry.prototype.toNumberArray = function (origin) {
  39363. if (Array.isArray(origin)) {
  39364. return origin;
  39365. }
  39366. else {
  39367. return Array.prototype.slice.call(origin);
  39368. }
  39369. };
  39370. /**
  39371. * Serialize all vertices data into a JSON oject
  39372. * @returns a JSON representation of the current geometry data
  39373. */
  39374. Geometry.prototype.serializeVerticeData = function () {
  39375. var serializationObject = this.serialize();
  39376. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39377. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39378. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39379. serializationObject.positions._updatable = true;
  39380. }
  39381. }
  39382. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39383. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39384. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39385. serializationObject.normals._updatable = true;
  39386. }
  39387. }
  39388. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39389. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39390. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39391. serializationObject.tangets._updatable = true;
  39392. }
  39393. }
  39394. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39395. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39396. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39397. serializationObject.uvs._updatable = true;
  39398. }
  39399. }
  39400. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39401. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39402. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39403. serializationObject.uv2s._updatable = true;
  39404. }
  39405. }
  39406. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39407. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39408. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39409. serializationObject.uv3s._updatable = true;
  39410. }
  39411. }
  39412. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39413. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39414. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39415. serializationObject.uv4s._updatable = true;
  39416. }
  39417. }
  39418. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39419. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39420. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39421. serializationObject.uv5s._updatable = true;
  39422. }
  39423. }
  39424. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39425. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39426. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39427. serializationObject.uv6s._updatable = true;
  39428. }
  39429. }
  39430. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39431. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39432. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39433. serializationObject.colors._updatable = true;
  39434. }
  39435. }
  39436. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39437. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39438. serializationObject.matricesIndices._isExpanded = true;
  39439. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39440. serializationObject.matricesIndices._updatable = true;
  39441. }
  39442. }
  39443. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39444. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39445. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39446. serializationObject.matricesWeights._updatable = true;
  39447. }
  39448. }
  39449. serializationObject.indices = this.toNumberArray(this.getIndices());
  39450. return serializationObject;
  39451. };
  39452. // Statics
  39453. /**
  39454. * Extracts a clone of a mesh geometry
  39455. * @param mesh defines the source mesh
  39456. * @param id defines the unique ID of the new geometry object
  39457. * @returns the new geometry object
  39458. */
  39459. Geometry.ExtractFromMesh = function (mesh, id) {
  39460. var geometry = mesh._geometry;
  39461. if (!geometry) {
  39462. return null;
  39463. }
  39464. return geometry.copy(id);
  39465. };
  39466. /**
  39467. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39468. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39469. * Be aware Math.random() could cause collisions, but:
  39470. * "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"
  39471. * @returns a string containing a new GUID
  39472. */
  39473. Geometry.RandomId = function () {
  39474. return BABYLON.Tools.RandomId();
  39475. };
  39476. /** @hidden */
  39477. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39478. var scene = mesh.getScene();
  39479. // Geometry
  39480. var geometryId = parsedGeometry.geometryId;
  39481. if (geometryId) {
  39482. var geometry = scene.getGeometryByID(geometryId);
  39483. if (geometry) {
  39484. geometry.applyToMesh(mesh);
  39485. }
  39486. }
  39487. else if (parsedGeometry instanceof ArrayBuffer) {
  39488. var binaryInfo = mesh._binaryInfo;
  39489. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39490. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39491. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39492. }
  39493. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39494. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39496. }
  39497. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39498. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39499. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39500. }
  39501. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39502. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39503. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39504. }
  39505. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39506. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39508. }
  39509. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39510. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39511. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39512. }
  39513. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39514. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39515. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39516. }
  39517. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39518. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39519. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39520. }
  39521. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39522. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39523. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39524. }
  39525. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39526. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39527. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39528. }
  39529. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39530. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39531. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39532. }
  39533. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39534. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39535. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39536. }
  39537. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39538. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39539. mesh.setIndices(indicesData, null);
  39540. }
  39541. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39542. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39543. mesh.subMeshes = [];
  39544. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39545. var materialIndex = subMeshesData[(i * 5) + 0];
  39546. var verticesStart = subMeshesData[(i * 5) + 1];
  39547. var verticesCount = subMeshesData[(i * 5) + 2];
  39548. var indexStart = subMeshesData[(i * 5) + 3];
  39549. var indexCount = subMeshesData[(i * 5) + 4];
  39550. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39551. }
  39552. }
  39553. }
  39554. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39555. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39556. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39557. if (parsedGeometry.tangents) {
  39558. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39559. }
  39560. if (parsedGeometry.uvs) {
  39561. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39562. }
  39563. if (parsedGeometry.uvs2) {
  39564. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39565. }
  39566. if (parsedGeometry.uvs3) {
  39567. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39568. }
  39569. if (parsedGeometry.uvs4) {
  39570. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39571. }
  39572. if (parsedGeometry.uvs5) {
  39573. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39574. }
  39575. if (parsedGeometry.uvs6) {
  39576. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39577. }
  39578. if (parsedGeometry.colors) {
  39579. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39580. }
  39581. if (parsedGeometry.matricesIndices) {
  39582. if (!parsedGeometry.matricesIndices._isExpanded) {
  39583. var floatIndices = [];
  39584. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39585. var matricesIndex = parsedGeometry.matricesIndices[i];
  39586. floatIndices.push(matricesIndex & 0x000000FF);
  39587. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39588. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39589. floatIndices.push(matricesIndex >> 24);
  39590. }
  39591. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39592. }
  39593. else {
  39594. delete parsedGeometry.matricesIndices._isExpanded;
  39595. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39596. }
  39597. }
  39598. if (parsedGeometry.matricesIndicesExtra) {
  39599. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39600. var floatIndices = [];
  39601. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39602. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39603. floatIndices.push(matricesIndex & 0x000000FF);
  39604. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39605. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39606. floatIndices.push(matricesIndex >> 24);
  39607. }
  39608. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39609. }
  39610. else {
  39611. delete parsedGeometry.matricesIndices._isExpanded;
  39612. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39613. }
  39614. }
  39615. if (parsedGeometry.matricesWeights) {
  39616. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39617. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39618. }
  39619. if (parsedGeometry.matricesWeightsExtra) {
  39620. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39621. }
  39622. mesh.setIndices(parsedGeometry.indices, null);
  39623. }
  39624. // SubMeshes
  39625. if (parsedGeometry.subMeshes) {
  39626. mesh.subMeshes = [];
  39627. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39628. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39629. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39630. }
  39631. }
  39632. // Flat shading
  39633. if (mesh._shouldGenerateFlatShading) {
  39634. mesh.convertToFlatShadedMesh();
  39635. delete mesh._shouldGenerateFlatShading;
  39636. }
  39637. // Update
  39638. mesh.computeWorldMatrix(true);
  39639. // Octree
  39640. var sceneOctree = scene.selectionOctree;
  39641. if (sceneOctree !== undefined && sceneOctree !== null) {
  39642. sceneOctree.addMesh(mesh);
  39643. }
  39644. };
  39645. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39646. var epsilon = 1e-3;
  39647. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39648. return;
  39649. }
  39650. var noInfluenceBoneIndex = 0.0;
  39651. if (parsedGeometry.skeletonId > -1) {
  39652. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39653. if (!skeleton) {
  39654. return;
  39655. }
  39656. noInfluenceBoneIndex = skeleton.bones.length;
  39657. }
  39658. else {
  39659. return;
  39660. }
  39661. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39662. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39663. var matricesWeights = parsedGeometry.matricesWeights;
  39664. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39665. var influencers = parsedGeometry.numBoneInfluencer;
  39666. var size = matricesWeights.length;
  39667. for (var i = 0; i < size; i += 4) {
  39668. var weight = 0.0;
  39669. var firstZeroWeight = -1;
  39670. for (var j = 0; j < 4; j++) {
  39671. var w = matricesWeights[i + j];
  39672. weight += w;
  39673. if (w < epsilon && firstZeroWeight < 0) {
  39674. firstZeroWeight = j;
  39675. }
  39676. }
  39677. if (matricesWeightsExtra) {
  39678. for (var j = 0; j < 4; j++) {
  39679. var w = matricesWeightsExtra[i + j];
  39680. weight += w;
  39681. if (w < epsilon && firstZeroWeight < 0) {
  39682. firstZeroWeight = j + 4;
  39683. }
  39684. }
  39685. }
  39686. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39687. firstZeroWeight = influencers - 1;
  39688. }
  39689. if (weight > epsilon) {
  39690. var mweight = 1.0 / weight;
  39691. for (var j = 0; j < 4; j++) {
  39692. matricesWeights[i + j] *= mweight;
  39693. }
  39694. if (matricesWeightsExtra) {
  39695. for (var j = 0; j < 4; j++) {
  39696. matricesWeightsExtra[i + j] *= mweight;
  39697. }
  39698. }
  39699. }
  39700. else {
  39701. if (firstZeroWeight >= 4) {
  39702. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39703. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39704. }
  39705. else {
  39706. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39707. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39708. }
  39709. }
  39710. }
  39711. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39712. if (parsedGeometry.matricesWeightsExtra) {
  39713. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39714. }
  39715. };
  39716. /**
  39717. * Create a new geometry from persisted data (Using .babylon file format)
  39718. * @param parsedVertexData defines the persisted data
  39719. * @param scene defines the hosting scene
  39720. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39721. * @returns the new geometry object
  39722. */
  39723. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39724. if (scene.getGeometryByID(parsedVertexData.id)) {
  39725. return null; // null since geometry could be something else than a box...
  39726. }
  39727. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39728. if (BABYLON.Tags) {
  39729. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39730. }
  39731. if (parsedVertexData.delayLoadingFile) {
  39732. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39733. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39734. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39735. geometry._delayInfo = [];
  39736. if (parsedVertexData.hasUVs) {
  39737. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39738. }
  39739. if (parsedVertexData.hasUVs2) {
  39740. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39741. }
  39742. if (parsedVertexData.hasUVs3) {
  39743. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39744. }
  39745. if (parsedVertexData.hasUVs4) {
  39746. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39747. }
  39748. if (parsedVertexData.hasUVs5) {
  39749. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39750. }
  39751. if (parsedVertexData.hasUVs6) {
  39752. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39753. }
  39754. if (parsedVertexData.hasColors) {
  39755. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39756. }
  39757. if (parsedVertexData.hasMatricesIndices) {
  39758. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39759. }
  39760. if (parsedVertexData.hasMatricesWeights) {
  39761. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39762. }
  39763. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39764. }
  39765. else {
  39766. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39767. }
  39768. scene.pushGeometry(geometry, true);
  39769. return geometry;
  39770. };
  39771. return Geometry;
  39772. }());
  39773. BABYLON.Geometry = Geometry;
  39774. // Primitives
  39775. /// Abstract class
  39776. /**
  39777. * Abstract class used to provide common services for all typed geometries
  39778. * @hidden
  39779. */
  39780. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39781. __extends(_PrimitiveGeometry, _super);
  39782. /**
  39783. * Creates a new typed geometry
  39784. * @param id defines the unique ID of the geometry
  39785. * @param scene defines the hosting scene
  39786. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39787. * @param mesh defines the hosting mesh (can be null)
  39788. */
  39789. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39790. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39791. if (mesh === void 0) { mesh = null; }
  39792. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39793. _this._canBeRegenerated = _canBeRegenerated;
  39794. _this._beingRegenerated = true;
  39795. _this.regenerate();
  39796. _this._beingRegenerated = false;
  39797. return _this;
  39798. }
  39799. /**
  39800. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39801. * @returns true if the geometry can be regenerated
  39802. */
  39803. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39804. return this._canBeRegenerated;
  39805. };
  39806. /**
  39807. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39808. */
  39809. _PrimitiveGeometry.prototype.regenerate = function () {
  39810. if (!this._canBeRegenerated) {
  39811. return;
  39812. }
  39813. this._beingRegenerated = true;
  39814. this.setAllVerticesData(this._regenerateVertexData(), false);
  39815. this._beingRegenerated = false;
  39816. };
  39817. /**
  39818. * Clone the geometry
  39819. * @param id defines the unique ID of the new geometry
  39820. * @returns the new geometry
  39821. */
  39822. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39823. return _super.prototype.copy.call(this, id);
  39824. };
  39825. // overrides
  39826. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39827. if (!this._beingRegenerated) {
  39828. return;
  39829. }
  39830. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39831. };
  39832. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39833. if (!this._beingRegenerated) {
  39834. return;
  39835. }
  39836. _super.prototype.setVerticesData.call(this, kind, data, false);
  39837. };
  39838. // to override
  39839. /** @hidden */
  39840. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39841. throw new Error("Abstract method");
  39842. };
  39843. _PrimitiveGeometry.prototype.copy = function (id) {
  39844. throw new Error("Must be overriden in sub-classes.");
  39845. };
  39846. _PrimitiveGeometry.prototype.serialize = function () {
  39847. var serializationObject = _super.prototype.serialize.call(this);
  39848. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39849. return serializationObject;
  39850. };
  39851. return _PrimitiveGeometry;
  39852. }(Geometry));
  39853. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39854. /**
  39855. * Creates a ribbon geometry
  39856. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39857. */
  39858. var RibbonGeometry = /** @class */ (function (_super) {
  39859. __extends(RibbonGeometry, _super);
  39860. /**
  39861. * Creates a ribbon geometry
  39862. * @param id defines the unique ID of the geometry
  39863. * @param scene defines the hosting scene
  39864. * @param pathArray defines the array of paths to use
  39865. * @param closeArray defines if the last path and the first path must be joined
  39866. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39867. * @param offset defines the offset between points
  39868. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39869. * @param mesh defines the hosting mesh (can be null)
  39870. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39871. */
  39872. function RibbonGeometry(id, scene,
  39873. /**
  39874. * Defines the array of paths to use
  39875. */
  39876. pathArray,
  39877. /**
  39878. * Defines if the last and first points of each path in your pathArray must be joined
  39879. */
  39880. closeArray,
  39881. /**
  39882. * Defines if the last and first points of each path in your pathArray must be joined
  39883. */
  39884. closePath,
  39885. /**
  39886. * Defines the offset between points
  39887. */
  39888. offset, canBeRegenerated, mesh,
  39889. /**
  39890. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39891. */
  39892. side) {
  39893. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39894. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39895. _this.pathArray = pathArray;
  39896. _this.closeArray = closeArray;
  39897. _this.closePath = closePath;
  39898. _this.offset = offset;
  39899. _this.side = side;
  39900. return _this;
  39901. }
  39902. /** @hidden */
  39903. RibbonGeometry.prototype._regenerateVertexData = function () {
  39904. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39905. };
  39906. RibbonGeometry.prototype.copy = function (id) {
  39907. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39908. };
  39909. return RibbonGeometry;
  39910. }(_PrimitiveGeometry));
  39911. BABYLON.RibbonGeometry = RibbonGeometry;
  39912. /**
  39913. * Creates a box geometry
  39914. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39915. */
  39916. var BoxGeometry = /** @class */ (function (_super) {
  39917. __extends(BoxGeometry, _super);
  39918. /**
  39919. * Creates a box geometry
  39920. * @param id defines the unique ID of the geometry
  39921. * @param scene defines the hosting scene
  39922. * @param size defines the zise of the box (width, height and depth are the same)
  39923. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39924. * @param mesh defines the hosting mesh (can be null)
  39925. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39926. */
  39927. function BoxGeometry(id, scene,
  39928. /**
  39929. * Defines the zise of the box (width, height and depth are the same)
  39930. */
  39931. size, canBeRegenerated, mesh,
  39932. /**
  39933. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39934. */
  39935. side) {
  39936. if (mesh === void 0) { mesh = null; }
  39937. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39938. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39939. _this.size = size;
  39940. _this.side = side;
  39941. return _this;
  39942. }
  39943. BoxGeometry.prototype._regenerateVertexData = function () {
  39944. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39945. };
  39946. BoxGeometry.prototype.copy = function (id) {
  39947. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39948. };
  39949. BoxGeometry.prototype.serialize = function () {
  39950. var serializationObject = _super.prototype.serialize.call(this);
  39951. serializationObject.size = this.size;
  39952. return serializationObject;
  39953. };
  39954. BoxGeometry.Parse = function (parsedBox, scene) {
  39955. if (scene.getGeometryByID(parsedBox.id)) {
  39956. return null; // null since geometry could be something else than a box...
  39957. }
  39958. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39959. if (BABYLON.Tags) {
  39960. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39961. }
  39962. scene.pushGeometry(box, true);
  39963. return box;
  39964. };
  39965. return BoxGeometry;
  39966. }(_PrimitiveGeometry));
  39967. BABYLON.BoxGeometry = BoxGeometry;
  39968. /**
  39969. * Creates a sphere geometry
  39970. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39971. */
  39972. var SphereGeometry = /** @class */ (function (_super) {
  39973. __extends(SphereGeometry, _super);
  39974. /**
  39975. * Create a new sphere geometry
  39976. * @param id defines the unique ID of the geometry
  39977. * @param scene defines the hosting scene
  39978. * @param segments defines the number of segments to use to create the sphere
  39979. * @param diameter defines the diameter of the sphere
  39980. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39981. * @param mesh defines the hosting mesh (can be null)
  39982. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39983. */
  39984. function SphereGeometry(id, scene,
  39985. /**
  39986. * Defines the number of segments to use to create the sphere
  39987. */
  39988. segments,
  39989. /**
  39990. * Defines the diameter of the sphere
  39991. */
  39992. diameter, canBeRegenerated, mesh,
  39993. /**
  39994. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39995. */
  39996. side) {
  39997. if (mesh === void 0) { mesh = null; }
  39998. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39999. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40000. _this.segments = segments;
  40001. _this.diameter = diameter;
  40002. _this.side = side;
  40003. return _this;
  40004. }
  40005. SphereGeometry.prototype._regenerateVertexData = function () {
  40006. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40007. };
  40008. SphereGeometry.prototype.copy = function (id) {
  40009. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40010. };
  40011. SphereGeometry.prototype.serialize = function () {
  40012. var serializationObject = _super.prototype.serialize.call(this);
  40013. serializationObject.segments = this.segments;
  40014. serializationObject.diameter = this.diameter;
  40015. return serializationObject;
  40016. };
  40017. SphereGeometry.Parse = function (parsedSphere, scene) {
  40018. if (scene.getGeometryByID(parsedSphere.id)) {
  40019. return null; // null since geometry could be something else than a sphere...
  40020. }
  40021. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40022. if (BABYLON.Tags) {
  40023. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40024. }
  40025. scene.pushGeometry(sphere, true);
  40026. return sphere;
  40027. };
  40028. return SphereGeometry;
  40029. }(_PrimitiveGeometry));
  40030. BABYLON.SphereGeometry = SphereGeometry;
  40031. /**
  40032. * Creates a disc geometry
  40033. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40034. */
  40035. var DiscGeometry = /** @class */ (function (_super) {
  40036. __extends(DiscGeometry, _super);
  40037. /**
  40038. * Creates a new disc geometry
  40039. * @param id defines the unique ID of the geometry
  40040. * @param scene defines the hosting scene
  40041. * @param radius defines the radius of the disc
  40042. * @param tessellation defines the tesselation factor to apply to the disc
  40043. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40044. * @param mesh defines the hosting mesh (can be null)
  40045. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40046. */
  40047. function DiscGeometry(id, scene,
  40048. /**
  40049. * Defines the radius of the disc
  40050. */
  40051. radius,
  40052. /**
  40053. * Defines the tesselation factor to apply to the disc
  40054. */
  40055. tessellation, canBeRegenerated, mesh,
  40056. /**
  40057. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40058. */
  40059. side) {
  40060. if (mesh === void 0) { mesh = null; }
  40061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40063. _this.radius = radius;
  40064. _this.tessellation = tessellation;
  40065. _this.side = side;
  40066. return _this;
  40067. }
  40068. DiscGeometry.prototype._regenerateVertexData = function () {
  40069. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40070. };
  40071. DiscGeometry.prototype.copy = function (id) {
  40072. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40073. };
  40074. return DiscGeometry;
  40075. }(_PrimitiveGeometry));
  40076. BABYLON.DiscGeometry = DiscGeometry;
  40077. /**
  40078. * Creates a new cylinder geometry
  40079. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40080. */
  40081. var CylinderGeometry = /** @class */ (function (_super) {
  40082. __extends(CylinderGeometry, _super);
  40083. /**
  40084. * Creates a new cylinder geometry
  40085. * @param id defines the unique ID of the geometry
  40086. * @param scene defines the hosting scene
  40087. * @param height defines the height of the cylinder
  40088. * @param diameterTop defines the diameter of the cylinder's top cap
  40089. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40090. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40091. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40092. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40093. * @param mesh defines the hosting mesh (can be null)
  40094. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40095. */
  40096. function CylinderGeometry(id, scene,
  40097. /**
  40098. * Defines the height of the cylinder
  40099. */
  40100. height,
  40101. /**
  40102. * Defines the diameter of the cylinder's top cap
  40103. */
  40104. diameterTop,
  40105. /**
  40106. * Defines the diameter of the cylinder's bottom cap
  40107. */
  40108. diameterBottom,
  40109. /**
  40110. * Defines the tessellation factor to apply to the cylinder
  40111. */
  40112. tessellation,
  40113. /**
  40114. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40115. */
  40116. subdivisions, canBeRegenerated, mesh,
  40117. /**
  40118. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40119. */
  40120. side) {
  40121. if (subdivisions === void 0) { subdivisions = 1; }
  40122. if (mesh === void 0) { mesh = null; }
  40123. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40124. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40125. _this.height = height;
  40126. _this.diameterTop = diameterTop;
  40127. _this.diameterBottom = diameterBottom;
  40128. _this.tessellation = tessellation;
  40129. _this.subdivisions = subdivisions;
  40130. _this.side = side;
  40131. return _this;
  40132. }
  40133. CylinderGeometry.prototype._regenerateVertexData = function () {
  40134. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40135. };
  40136. CylinderGeometry.prototype.copy = function (id) {
  40137. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40138. };
  40139. CylinderGeometry.prototype.serialize = function () {
  40140. var serializationObject = _super.prototype.serialize.call(this);
  40141. serializationObject.height = this.height;
  40142. serializationObject.diameterTop = this.diameterTop;
  40143. serializationObject.diameterBottom = this.diameterBottom;
  40144. serializationObject.tessellation = this.tessellation;
  40145. return serializationObject;
  40146. };
  40147. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40148. if (scene.getGeometryByID(parsedCylinder.id)) {
  40149. return null; // null since geometry could be something else than a cylinder...
  40150. }
  40151. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40152. if (BABYLON.Tags) {
  40153. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40154. }
  40155. scene.pushGeometry(cylinder, true);
  40156. return cylinder;
  40157. };
  40158. return CylinderGeometry;
  40159. }(_PrimitiveGeometry));
  40160. BABYLON.CylinderGeometry = CylinderGeometry;
  40161. /**
  40162. * Creates a new torus geometry
  40163. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40164. */
  40165. var TorusGeometry = /** @class */ (function (_super) {
  40166. __extends(TorusGeometry, _super);
  40167. /**
  40168. * Creates a new torus geometry
  40169. * @param id defines the unique ID of the geometry
  40170. * @param scene defines the hosting scene
  40171. * @param diameter defines the diameter of the torus
  40172. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40173. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40174. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40175. * @param mesh defines the hosting mesh (can be null)
  40176. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40177. */
  40178. function TorusGeometry(id, scene,
  40179. /**
  40180. * Defines the diameter of the torus
  40181. */
  40182. diameter,
  40183. /**
  40184. * Defines the thickness of the torus (ie. internal diameter)
  40185. */
  40186. thickness,
  40187. /**
  40188. * Defines the tesselation factor to apply to the torus
  40189. */
  40190. tessellation, canBeRegenerated, mesh,
  40191. /**
  40192. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40193. */
  40194. side) {
  40195. if (mesh === void 0) { mesh = null; }
  40196. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40197. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40198. _this.diameter = diameter;
  40199. _this.thickness = thickness;
  40200. _this.tessellation = tessellation;
  40201. _this.side = side;
  40202. return _this;
  40203. }
  40204. TorusGeometry.prototype._regenerateVertexData = function () {
  40205. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40206. };
  40207. TorusGeometry.prototype.copy = function (id) {
  40208. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40209. };
  40210. TorusGeometry.prototype.serialize = function () {
  40211. var serializationObject = _super.prototype.serialize.call(this);
  40212. serializationObject.diameter = this.diameter;
  40213. serializationObject.thickness = this.thickness;
  40214. serializationObject.tessellation = this.tessellation;
  40215. return serializationObject;
  40216. };
  40217. TorusGeometry.Parse = function (parsedTorus, scene) {
  40218. if (scene.getGeometryByID(parsedTorus.id)) {
  40219. return null; // null since geometry could be something else than a torus...
  40220. }
  40221. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40222. if (BABYLON.Tags) {
  40223. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40224. }
  40225. scene.pushGeometry(torus, true);
  40226. return torus;
  40227. };
  40228. return TorusGeometry;
  40229. }(_PrimitiveGeometry));
  40230. BABYLON.TorusGeometry = TorusGeometry;
  40231. /**
  40232. * Creates a new ground geometry
  40233. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40234. */
  40235. var GroundGeometry = /** @class */ (function (_super) {
  40236. __extends(GroundGeometry, _super);
  40237. /**
  40238. * Creates a new ground geometry
  40239. * @param id defines the unique ID of the geometry
  40240. * @param scene defines the hosting scene
  40241. * @param width defines the width of the ground
  40242. * @param height defines the height of the ground
  40243. * @param subdivisions defines the subdivisions to apply to the ground
  40244. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40245. * @param mesh defines the hosting mesh (can be null)
  40246. */
  40247. function GroundGeometry(id, scene,
  40248. /**
  40249. * Defines the width of the ground
  40250. */
  40251. width,
  40252. /**
  40253. * Defines the height of the ground
  40254. */
  40255. height,
  40256. /**
  40257. * Defines the subdivisions to apply to the ground
  40258. */
  40259. subdivisions, canBeRegenerated, mesh) {
  40260. if (mesh === void 0) { mesh = null; }
  40261. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40262. _this.width = width;
  40263. _this.height = height;
  40264. _this.subdivisions = subdivisions;
  40265. return _this;
  40266. }
  40267. GroundGeometry.prototype._regenerateVertexData = function () {
  40268. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40269. };
  40270. GroundGeometry.prototype.copy = function (id) {
  40271. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40272. };
  40273. GroundGeometry.prototype.serialize = function () {
  40274. var serializationObject = _super.prototype.serialize.call(this);
  40275. serializationObject.width = this.width;
  40276. serializationObject.height = this.height;
  40277. serializationObject.subdivisions = this.subdivisions;
  40278. return serializationObject;
  40279. };
  40280. GroundGeometry.Parse = function (parsedGround, scene) {
  40281. if (scene.getGeometryByID(parsedGround.id)) {
  40282. return null; // null since geometry could be something else than a ground...
  40283. }
  40284. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40285. if (BABYLON.Tags) {
  40286. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40287. }
  40288. scene.pushGeometry(ground, true);
  40289. return ground;
  40290. };
  40291. return GroundGeometry;
  40292. }(_PrimitiveGeometry));
  40293. BABYLON.GroundGeometry = GroundGeometry;
  40294. /**
  40295. * Creates a tiled ground geometry
  40296. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40297. */
  40298. var TiledGroundGeometry = /** @class */ (function (_super) {
  40299. __extends(TiledGroundGeometry, _super);
  40300. /**
  40301. * Creates a tiled ground geometry
  40302. * @param id defines the unique ID of the geometry
  40303. * @param scene defines the hosting scene
  40304. * @param xmin defines the minimum value on X axis
  40305. * @param zmin defines the minimum value on Z axis
  40306. * @param xmax defines the maximum value on X axis
  40307. * @param zmax defines the maximum value on Z axis
  40308. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40309. * @param precision defines the precision to use when computing the tiles
  40310. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40311. * @param mesh defines the hosting mesh (can be null)
  40312. */
  40313. function TiledGroundGeometry(id, scene,
  40314. /**
  40315. * Defines the minimum value on X axis
  40316. */
  40317. xmin,
  40318. /**
  40319. * Defines the minimum value on Z axis
  40320. */
  40321. zmin,
  40322. /**
  40323. * Defines the maximum value on X axis
  40324. */
  40325. xmax,
  40326. /**
  40327. * Defines the maximum value on Z axis
  40328. */
  40329. zmax,
  40330. /**
  40331. * Defines the subdivisions to apply to the ground
  40332. */
  40333. subdivisions,
  40334. /**
  40335. * Defines the precision to use when computing the tiles
  40336. */
  40337. precision, canBeRegenerated, mesh) {
  40338. if (mesh === void 0) { mesh = null; }
  40339. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40340. _this.xmin = xmin;
  40341. _this.zmin = zmin;
  40342. _this.xmax = xmax;
  40343. _this.zmax = zmax;
  40344. _this.subdivisions = subdivisions;
  40345. _this.precision = precision;
  40346. return _this;
  40347. }
  40348. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40349. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40350. };
  40351. TiledGroundGeometry.prototype.copy = function (id) {
  40352. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40353. };
  40354. return TiledGroundGeometry;
  40355. }(_PrimitiveGeometry));
  40356. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40357. /**
  40358. * Creates a plane geometry
  40359. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40360. */
  40361. var PlaneGeometry = /** @class */ (function (_super) {
  40362. __extends(PlaneGeometry, _super);
  40363. /**
  40364. * Creates a plane geometry
  40365. * @param id defines the unique ID of the geometry
  40366. * @param scene defines the hosting scene
  40367. * @param size defines the size of the plane (width === height)
  40368. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40369. * @param mesh defines the hosting mesh (can be null)
  40370. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40371. */
  40372. function PlaneGeometry(id, scene,
  40373. /**
  40374. * Defines the size of the plane (width === height)
  40375. */
  40376. size, canBeRegenerated, mesh,
  40377. /**
  40378. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40379. */
  40380. side) {
  40381. if (mesh === void 0) { mesh = null; }
  40382. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40383. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40384. _this.size = size;
  40385. _this.side = side;
  40386. return _this;
  40387. }
  40388. PlaneGeometry.prototype._regenerateVertexData = function () {
  40389. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40390. };
  40391. PlaneGeometry.prototype.copy = function (id) {
  40392. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40393. };
  40394. PlaneGeometry.prototype.serialize = function () {
  40395. var serializationObject = _super.prototype.serialize.call(this);
  40396. serializationObject.size = this.size;
  40397. return serializationObject;
  40398. };
  40399. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40400. if (scene.getGeometryByID(parsedPlane.id)) {
  40401. return null; // null since geometry could be something else than a ground...
  40402. }
  40403. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40404. if (BABYLON.Tags) {
  40405. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40406. }
  40407. scene.pushGeometry(plane, true);
  40408. return plane;
  40409. };
  40410. return PlaneGeometry;
  40411. }(_PrimitiveGeometry));
  40412. BABYLON.PlaneGeometry = PlaneGeometry;
  40413. /**
  40414. * Creates a torus knot geometry
  40415. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40416. */
  40417. var TorusKnotGeometry = /** @class */ (function (_super) {
  40418. __extends(TorusKnotGeometry, _super);
  40419. /**
  40420. * Creates a torus knot geometry
  40421. * @param id defines the unique ID of the geometry
  40422. * @param scene defines the hosting scene
  40423. * @param radius defines the radius of the torus knot
  40424. * @param tube defines the thickness of the torus knot tube
  40425. * @param radialSegments defines the number of radial segments
  40426. * @param tubularSegments defines the number of tubular segments
  40427. * @param p defines the first number of windings
  40428. * @param q defines the second number of windings
  40429. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40430. * @param mesh defines the hosting mesh (can be null)
  40431. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40432. */
  40433. function TorusKnotGeometry(id, scene,
  40434. /**
  40435. * Defines the radius of the torus knot
  40436. */
  40437. radius,
  40438. /**
  40439. * Defines the thickness of the torus knot tube
  40440. */
  40441. tube,
  40442. /**
  40443. * Defines the number of radial segments
  40444. */
  40445. radialSegments,
  40446. /**
  40447. * Defines the number of tubular segments
  40448. */
  40449. tubularSegments,
  40450. /**
  40451. * Defines the first number of windings
  40452. */
  40453. p,
  40454. /**
  40455. * Defines the second number of windings
  40456. */
  40457. q, canBeRegenerated, mesh,
  40458. /**
  40459. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40460. */
  40461. side) {
  40462. if (mesh === void 0) { mesh = null; }
  40463. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40464. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40465. _this.radius = radius;
  40466. _this.tube = tube;
  40467. _this.radialSegments = radialSegments;
  40468. _this.tubularSegments = tubularSegments;
  40469. _this.p = p;
  40470. _this.q = q;
  40471. _this.side = side;
  40472. return _this;
  40473. }
  40474. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40475. 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 });
  40476. };
  40477. TorusKnotGeometry.prototype.copy = function (id) {
  40478. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40479. };
  40480. TorusKnotGeometry.prototype.serialize = function () {
  40481. var serializationObject = _super.prototype.serialize.call(this);
  40482. serializationObject.radius = this.radius;
  40483. serializationObject.tube = this.tube;
  40484. serializationObject.radialSegments = this.radialSegments;
  40485. serializationObject.tubularSegments = this.tubularSegments;
  40486. serializationObject.p = this.p;
  40487. serializationObject.q = this.q;
  40488. return serializationObject;
  40489. };
  40490. ;
  40491. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40492. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40493. return null; // null since geometry could be something else than a ground...
  40494. }
  40495. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40496. if (BABYLON.Tags) {
  40497. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40498. }
  40499. scene.pushGeometry(torusKnot, true);
  40500. return torusKnot;
  40501. };
  40502. return TorusKnotGeometry;
  40503. }(_PrimitiveGeometry));
  40504. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40505. //}
  40506. })(BABYLON || (BABYLON = {}));
  40507. //# sourceMappingURL=babylon.geometry.js.map
  40508. var BABYLON;
  40509. (function (BABYLON) {
  40510. /**
  40511. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40512. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40513. */
  40514. var PostProcessManager = /** @class */ (function () {
  40515. /**
  40516. * Creates a new instance PostProcess
  40517. * @param scene The scene that the post process is associated with.
  40518. */
  40519. function PostProcessManager(scene) {
  40520. this._vertexBuffers = {};
  40521. this._scene = scene;
  40522. }
  40523. PostProcessManager.prototype._prepareBuffers = function () {
  40524. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40525. return;
  40526. }
  40527. // VBO
  40528. var vertices = [];
  40529. vertices.push(1, 1);
  40530. vertices.push(-1, 1);
  40531. vertices.push(-1, -1);
  40532. vertices.push(1, -1);
  40533. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40534. this._buildIndexBuffer();
  40535. };
  40536. PostProcessManager.prototype._buildIndexBuffer = function () {
  40537. // Indices
  40538. var indices = [];
  40539. indices.push(0);
  40540. indices.push(1);
  40541. indices.push(2);
  40542. indices.push(0);
  40543. indices.push(2);
  40544. indices.push(3);
  40545. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40546. };
  40547. /**
  40548. * Rebuilds the vertex buffers of the manager.
  40549. */
  40550. PostProcessManager.prototype._rebuild = function () {
  40551. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40552. if (!vb) {
  40553. return;
  40554. }
  40555. vb._rebuild();
  40556. this._buildIndexBuffer();
  40557. };
  40558. // Methods
  40559. /**
  40560. * Prepares a frame to be run through a post process.
  40561. * @param sourceTexture The input texture to the post procesess. (default: null)
  40562. * @param postProcesses An array of post processes to be run. (default: null)
  40563. * @returns True if the post processes were able to be run.
  40564. */
  40565. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40566. if (sourceTexture === void 0) { sourceTexture = null; }
  40567. if (postProcesses === void 0) { postProcesses = null; }
  40568. var camera = this._scene.activeCamera;
  40569. if (!camera) {
  40570. return false;
  40571. }
  40572. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40573. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40574. return false;
  40575. }
  40576. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40577. return true;
  40578. };
  40579. /**
  40580. * Manually render a set of post processes to a texture.
  40581. * @param postProcesses An array of post processes to be run.
  40582. * @param targetTexture The target texture to render to.
  40583. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40584. */
  40585. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40586. if (targetTexture === void 0) { targetTexture = null; }
  40587. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40588. var engine = this._scene.getEngine();
  40589. for (var index = 0; index < postProcesses.length; index++) {
  40590. if (index < postProcesses.length - 1) {
  40591. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40592. }
  40593. else {
  40594. if (targetTexture) {
  40595. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40596. }
  40597. else {
  40598. engine.restoreDefaultFramebuffer();
  40599. }
  40600. }
  40601. var pp = postProcesses[index];
  40602. var effect = pp.apply();
  40603. if (effect) {
  40604. pp.onBeforeRenderObservable.notifyObservers(effect);
  40605. // VBOs
  40606. this._prepareBuffers();
  40607. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40608. // Draw order
  40609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40610. pp.onAfterRenderObservable.notifyObservers(effect);
  40611. }
  40612. }
  40613. // Restore depth buffer
  40614. engine.setDepthBuffer(true);
  40615. engine.setDepthWrite(true);
  40616. };
  40617. /**
  40618. * Finalize the result of the output of the postprocesses.
  40619. * @param doNotPresent If true the result will not be displayed to the screen.
  40620. * @param targetTexture The target texture to render to.
  40621. * @param faceIndex The index of the face to bind the target texture to.
  40622. * @param postProcesses The array of post processes to render.
  40623. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40624. */
  40625. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40626. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40627. var camera = this._scene.activeCamera;
  40628. if (!camera) {
  40629. return;
  40630. }
  40631. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40632. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40633. return;
  40634. }
  40635. var engine = this._scene.getEngine();
  40636. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40637. var pp = postProcesses[index];
  40638. if (index < len - 1) {
  40639. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40640. }
  40641. else {
  40642. if (targetTexture) {
  40643. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40644. pp._outputTexture = targetTexture;
  40645. }
  40646. else {
  40647. engine.restoreDefaultFramebuffer();
  40648. pp._outputTexture = null;
  40649. }
  40650. }
  40651. if (doNotPresent) {
  40652. break;
  40653. }
  40654. var effect = pp.apply();
  40655. if (effect) {
  40656. pp.onBeforeRenderObservable.notifyObservers(effect);
  40657. // VBOs
  40658. this._prepareBuffers();
  40659. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40660. // Draw order
  40661. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40662. pp.onAfterRenderObservable.notifyObservers(effect);
  40663. }
  40664. }
  40665. // Restore states
  40666. engine.setDepthBuffer(true);
  40667. engine.setDepthWrite(true);
  40668. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40669. };
  40670. /**
  40671. * Disposes of the post process manager.
  40672. */
  40673. PostProcessManager.prototype.dispose = function () {
  40674. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40675. if (buffer) {
  40676. buffer.dispose();
  40677. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40678. }
  40679. if (this._indexBuffer) {
  40680. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40681. this._indexBuffer = null;
  40682. }
  40683. };
  40684. return PostProcessManager;
  40685. }());
  40686. BABYLON.PostProcessManager = PostProcessManager;
  40687. })(BABYLON || (BABYLON = {}));
  40688. //# sourceMappingURL=babylon.postProcessManager.js.map
  40689. var BABYLON;
  40690. (function (BABYLON) {
  40691. /**
  40692. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40693. */
  40694. var PerformanceMonitor = /** @class */ (function () {
  40695. /**
  40696. * constructor
  40697. * @param frameSampleSize The number of samples required to saturate the sliding window
  40698. */
  40699. function PerformanceMonitor(frameSampleSize) {
  40700. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40701. this._enabled = true;
  40702. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40703. }
  40704. /**
  40705. * Samples current frame
  40706. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40707. */
  40708. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40709. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40710. if (!this._enabled)
  40711. return;
  40712. if (this._lastFrameTimeMs != null) {
  40713. var dt = timeMs - this._lastFrameTimeMs;
  40714. this._rollingFrameTime.add(dt);
  40715. }
  40716. this._lastFrameTimeMs = timeMs;
  40717. };
  40718. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40719. /**
  40720. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40721. * @return Average frame time in milliseconds
  40722. */
  40723. get: function () {
  40724. return this._rollingFrameTime.average;
  40725. },
  40726. enumerable: true,
  40727. configurable: true
  40728. });
  40729. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40730. /**
  40731. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40732. * @return Frame time variance in milliseconds squared
  40733. */
  40734. get: function () {
  40735. return this._rollingFrameTime.variance;
  40736. },
  40737. enumerable: true,
  40738. configurable: true
  40739. });
  40740. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40741. /**
  40742. * Returns the frame time of the most recent frame
  40743. * @return Frame time in milliseconds
  40744. */
  40745. get: function () {
  40746. return this._rollingFrameTime.history(0);
  40747. },
  40748. enumerable: true,
  40749. configurable: true
  40750. });
  40751. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40752. /**
  40753. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40754. * @return Framerate in frames per second
  40755. */
  40756. get: function () {
  40757. return 1000.0 / this._rollingFrameTime.average;
  40758. },
  40759. enumerable: true,
  40760. configurable: true
  40761. });
  40762. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40763. /**
  40764. * Returns the average framerate in frames per second using the most recent frame time
  40765. * @return Framerate in frames per second
  40766. */
  40767. get: function () {
  40768. var history = this._rollingFrameTime.history(0);
  40769. if (history === 0) {
  40770. return 0;
  40771. }
  40772. return 1000.0 / history;
  40773. },
  40774. enumerable: true,
  40775. configurable: true
  40776. });
  40777. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40778. /**
  40779. * Returns true if enough samples have been taken to completely fill the sliding window
  40780. * @return true if saturated
  40781. */
  40782. get: function () {
  40783. return this._rollingFrameTime.isSaturated();
  40784. },
  40785. enumerable: true,
  40786. configurable: true
  40787. });
  40788. /**
  40789. * Enables contributions to the sliding window sample set
  40790. */
  40791. PerformanceMonitor.prototype.enable = function () {
  40792. this._enabled = true;
  40793. };
  40794. /**
  40795. * Disables contributions to the sliding window sample set
  40796. * Samples will not be interpolated over the disabled period
  40797. */
  40798. PerformanceMonitor.prototype.disable = function () {
  40799. this._enabled = false;
  40800. //clear last sample to avoid interpolating over the disabled period when next enabled
  40801. this._lastFrameTimeMs = null;
  40802. };
  40803. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40804. /**
  40805. * Returns true if sampling is enabled
  40806. * @return true if enabled
  40807. */
  40808. get: function () {
  40809. return this._enabled;
  40810. },
  40811. enumerable: true,
  40812. configurable: true
  40813. });
  40814. /**
  40815. * Resets performance monitor
  40816. */
  40817. PerformanceMonitor.prototype.reset = function () {
  40818. //clear last sample to avoid interpolating over the disabled period when next enabled
  40819. this._lastFrameTimeMs = null;
  40820. //wipe record
  40821. this._rollingFrameTime.reset();
  40822. };
  40823. return PerformanceMonitor;
  40824. }());
  40825. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40826. /**
  40827. * RollingAverage
  40828. *
  40829. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40830. */
  40831. var RollingAverage = /** @class */ (function () {
  40832. /**
  40833. * constructor
  40834. * @param length The number of samples required to saturate the sliding window
  40835. */
  40836. function RollingAverage(length) {
  40837. this._samples = new Array(length);
  40838. this.reset();
  40839. }
  40840. /**
  40841. * Adds a sample to the sample set
  40842. * @param v The sample value
  40843. */
  40844. RollingAverage.prototype.add = function (v) {
  40845. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40846. var delta;
  40847. //we need to check if we've already wrapped round
  40848. if (this.isSaturated()) {
  40849. //remove bottom of stack from mean
  40850. var bottomValue = this._samples[this._pos];
  40851. delta = bottomValue - this.average;
  40852. this.average -= delta / (this._sampleCount - 1);
  40853. this._m2 -= delta * (bottomValue - this.average);
  40854. }
  40855. else {
  40856. this._sampleCount++;
  40857. }
  40858. //add new value to mean
  40859. delta = v - this.average;
  40860. this.average += delta / (this._sampleCount);
  40861. this._m2 += delta * (v - this.average);
  40862. //set the new variance
  40863. this.variance = this._m2 / (this._sampleCount - 1);
  40864. this._samples[this._pos] = v;
  40865. this._pos++;
  40866. this._pos %= this._samples.length; //positive wrap around
  40867. };
  40868. /**
  40869. * Returns previously added values or null if outside of history or outside the sliding window domain
  40870. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40871. * @return Value previously recorded with add() or null if outside of range
  40872. */
  40873. RollingAverage.prototype.history = function (i) {
  40874. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40875. return 0;
  40876. }
  40877. var i0 = this._wrapPosition(this._pos - 1.0);
  40878. return this._samples[this._wrapPosition(i0 - i)];
  40879. };
  40880. /**
  40881. * Returns true if enough samples have been taken to completely fill the sliding window
  40882. * @return true if sample-set saturated
  40883. */
  40884. RollingAverage.prototype.isSaturated = function () {
  40885. return this._sampleCount >= this._samples.length;
  40886. };
  40887. /**
  40888. * Resets the rolling average (equivalent to 0 samples taken so far)
  40889. */
  40890. RollingAverage.prototype.reset = function () {
  40891. this.average = 0;
  40892. this.variance = 0;
  40893. this._sampleCount = 0;
  40894. this._pos = 0;
  40895. this._m2 = 0;
  40896. };
  40897. /**
  40898. * Wraps a value around the sample range boundaries
  40899. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40900. * @return Wrapped position in sample range
  40901. */
  40902. RollingAverage.prototype._wrapPosition = function (i) {
  40903. var max = this._samples.length;
  40904. return ((i % max) + max) % max;
  40905. };
  40906. return RollingAverage;
  40907. }());
  40908. BABYLON.RollingAverage = RollingAverage;
  40909. })(BABYLON || (BABYLON = {}));
  40910. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40911. var BABYLON;
  40912. (function (BABYLON) {
  40913. /**
  40914. * This groups together the common properties used for image processing either in direct forward pass
  40915. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40916. * or not.
  40917. */
  40918. var ImageProcessingConfiguration = /** @class */ (function () {
  40919. function ImageProcessingConfiguration() {
  40920. /**
  40921. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40922. */
  40923. this.colorCurves = new BABYLON.ColorCurves();
  40924. this._colorCurvesEnabled = false;
  40925. this._colorGradingEnabled = false;
  40926. this._colorGradingWithGreenDepth = true;
  40927. this._colorGradingBGR = true;
  40928. this._exposure = 1.0;
  40929. this._toneMappingEnabled = false;
  40930. this._contrast = 1.0;
  40931. /**
  40932. * Vignette stretch size.
  40933. */
  40934. this.vignetteStretch = 0;
  40935. /**
  40936. * Vignette centre X Offset.
  40937. */
  40938. this.vignetteCentreX = 0;
  40939. /**
  40940. * Vignette centre Y Offset.
  40941. */
  40942. this.vignetteCentreY = 0;
  40943. /**
  40944. * Vignette weight or intensity of the vignette effect.
  40945. */
  40946. this.vignetteWeight = 1.5;
  40947. /**
  40948. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40949. * if vignetteEnabled is set to true.
  40950. */
  40951. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40952. /**
  40953. * Camera field of view used by the Vignette effect.
  40954. */
  40955. this.vignetteCameraFov = 0.5;
  40956. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40957. this._vignetteEnabled = false;
  40958. this._applyByPostProcess = false;
  40959. this._isEnabled = true;
  40960. /**
  40961. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40962. */
  40963. this.onUpdateParameters = new BABYLON.Observable();
  40964. }
  40965. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40966. /**
  40967. * Gets wether the color curves effect is enabled.
  40968. */
  40969. get: function () {
  40970. return this._colorCurvesEnabled;
  40971. },
  40972. /**
  40973. * Sets wether the color curves effect is enabled.
  40974. */
  40975. set: function (value) {
  40976. if (this._colorCurvesEnabled === value) {
  40977. return;
  40978. }
  40979. this._colorCurvesEnabled = value;
  40980. this._updateParameters();
  40981. },
  40982. enumerable: true,
  40983. configurable: true
  40984. });
  40985. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40986. /**
  40987. * Gets wether the color grading effect is enabled.
  40988. */
  40989. get: function () {
  40990. return this._colorGradingEnabled;
  40991. },
  40992. /**
  40993. * Sets wether the color grading effect is enabled.
  40994. */
  40995. set: function (value) {
  40996. if (this._colorGradingEnabled === value) {
  40997. return;
  40998. }
  40999. this._colorGradingEnabled = value;
  41000. this._updateParameters();
  41001. },
  41002. enumerable: true,
  41003. configurable: true
  41004. });
  41005. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41006. /**
  41007. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41008. */
  41009. get: function () {
  41010. return this._colorGradingWithGreenDepth;
  41011. },
  41012. /**
  41013. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41014. */
  41015. set: function (value) {
  41016. if (this._colorGradingWithGreenDepth === value) {
  41017. return;
  41018. }
  41019. this._colorGradingWithGreenDepth = value;
  41020. this._updateParameters();
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41026. /**
  41027. * Gets wether the color grading texture contains BGR values.
  41028. */
  41029. get: function () {
  41030. return this._colorGradingBGR;
  41031. },
  41032. /**
  41033. * Sets wether the color grading texture contains BGR values.
  41034. */
  41035. set: function (value) {
  41036. if (this._colorGradingBGR === value) {
  41037. return;
  41038. }
  41039. this._colorGradingBGR = value;
  41040. this._updateParameters();
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41046. /**
  41047. * Gets the Exposure used in the effect.
  41048. */
  41049. get: function () {
  41050. return this._exposure;
  41051. },
  41052. /**
  41053. * Sets the Exposure used in the effect.
  41054. */
  41055. set: function (value) {
  41056. if (this._exposure === value) {
  41057. return;
  41058. }
  41059. this._exposure = value;
  41060. this._updateParameters();
  41061. },
  41062. enumerable: true,
  41063. configurable: true
  41064. });
  41065. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41066. /**
  41067. * Gets wether the tone mapping effect is enabled.
  41068. */
  41069. get: function () {
  41070. return this._toneMappingEnabled;
  41071. },
  41072. /**
  41073. * Sets wether the tone mapping effect is enabled.
  41074. */
  41075. set: function (value) {
  41076. if (this._toneMappingEnabled === value) {
  41077. return;
  41078. }
  41079. this._toneMappingEnabled = value;
  41080. this._updateParameters();
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41086. /**
  41087. * Gets the contrast used in the effect.
  41088. */
  41089. get: function () {
  41090. return this._contrast;
  41091. },
  41092. /**
  41093. * Sets the contrast used in the effect.
  41094. */
  41095. set: function (value) {
  41096. if (this._contrast === value) {
  41097. return;
  41098. }
  41099. this._contrast = value;
  41100. this._updateParameters();
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41106. /**
  41107. * Gets the vignette blend mode allowing different kind of effect.
  41108. */
  41109. get: function () {
  41110. return this._vignetteBlendMode;
  41111. },
  41112. /**
  41113. * Sets the vignette blend mode allowing different kind of effect.
  41114. */
  41115. set: function (value) {
  41116. if (this._vignetteBlendMode === value) {
  41117. return;
  41118. }
  41119. this._vignetteBlendMode = value;
  41120. this._updateParameters();
  41121. },
  41122. enumerable: true,
  41123. configurable: true
  41124. });
  41125. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41126. /**
  41127. * Gets wether the vignette effect is enabled.
  41128. */
  41129. get: function () {
  41130. return this._vignetteEnabled;
  41131. },
  41132. /**
  41133. * Sets wether the vignette effect is enabled.
  41134. */
  41135. set: function (value) {
  41136. if (this._vignetteEnabled === value) {
  41137. return;
  41138. }
  41139. this._vignetteEnabled = value;
  41140. this._updateParameters();
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41146. /**
  41147. * Gets wether the image processing is applied through a post process or not.
  41148. */
  41149. get: function () {
  41150. return this._applyByPostProcess;
  41151. },
  41152. /**
  41153. * Sets wether the image processing is applied through a post process or not.
  41154. */
  41155. set: function (value) {
  41156. if (this._applyByPostProcess === value) {
  41157. return;
  41158. }
  41159. this._applyByPostProcess = value;
  41160. this._updateParameters();
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41166. /**
  41167. * Gets wether the image processing is enabled or not.
  41168. */
  41169. get: function () {
  41170. return this._isEnabled;
  41171. },
  41172. /**
  41173. * Sets wether the image processing is enabled or not.
  41174. */
  41175. set: function (value) {
  41176. if (this._isEnabled === value) {
  41177. return;
  41178. }
  41179. this._isEnabled = value;
  41180. this._updateParameters();
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. /**
  41186. * Method called each time the image processing information changes requires to recompile the effect.
  41187. */
  41188. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41189. this.onUpdateParameters.notifyObservers(this);
  41190. };
  41191. ImageProcessingConfiguration.prototype.getClassName = function () {
  41192. return "ImageProcessingConfiguration";
  41193. };
  41194. /**
  41195. * Prepare the list of uniforms associated with the Image Processing effects.
  41196. * @param uniformsList The list of uniforms used in the effect
  41197. * @param defines the list of defines currently in use
  41198. */
  41199. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41200. if (defines.EXPOSURE) {
  41201. uniforms.push("exposureLinear");
  41202. }
  41203. if (defines.CONTRAST) {
  41204. uniforms.push("contrast");
  41205. }
  41206. if (defines.COLORGRADING) {
  41207. uniforms.push("colorTransformSettings");
  41208. }
  41209. if (defines.VIGNETTE) {
  41210. uniforms.push("vInverseScreenSize");
  41211. uniforms.push("vignetteSettings1");
  41212. uniforms.push("vignetteSettings2");
  41213. }
  41214. if (defines.COLORCURVES) {
  41215. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41216. }
  41217. };
  41218. /**
  41219. * Prepare the list of samplers associated with the Image Processing effects.
  41220. * @param uniformsList The list of uniforms used in the effect
  41221. * @param defines the list of defines currently in use
  41222. */
  41223. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41224. if (defines.COLORGRADING) {
  41225. samplersList.push("txColorTransform");
  41226. }
  41227. };
  41228. /**
  41229. * Prepare the list of defines associated to the shader.
  41230. * @param defines the list of defines to complete
  41231. */
  41232. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41233. if (forPostProcess === void 0) { forPostProcess = false; }
  41234. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41235. defines.VIGNETTE = false;
  41236. defines.TONEMAPPING = false;
  41237. defines.CONTRAST = false;
  41238. defines.EXPOSURE = false;
  41239. defines.COLORCURVES = false;
  41240. defines.COLORGRADING = false;
  41241. defines.COLORGRADING3D = false;
  41242. defines.IMAGEPROCESSING = false;
  41243. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41244. return;
  41245. }
  41246. defines.VIGNETTE = this.vignetteEnabled;
  41247. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41248. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41249. defines.TONEMAPPING = this.toneMappingEnabled;
  41250. defines.CONTRAST = (this.contrast !== 1.0);
  41251. defines.EXPOSURE = (this.exposure !== 1.0);
  41252. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41253. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41254. if (defines.COLORGRADING) {
  41255. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41256. }
  41257. else {
  41258. defines.COLORGRADING3D = false;
  41259. }
  41260. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41261. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41262. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41263. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41264. };
  41265. /**
  41266. * Returns true if all the image processing information are ready.
  41267. */
  41268. ImageProcessingConfiguration.prototype.isReady = function () {
  41269. // Color Grading texure can not be none blocking.
  41270. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41271. };
  41272. /**
  41273. * Binds the image processing to the shader.
  41274. * @param effect The effect to bind to
  41275. */
  41276. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41277. if (aspectRatio === void 0) { aspectRatio = 1; }
  41278. // Color Curves
  41279. if (this._colorCurvesEnabled && this.colorCurves) {
  41280. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41281. }
  41282. // Vignette
  41283. if (this._vignetteEnabled) {
  41284. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41285. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41286. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41287. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41288. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41289. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41290. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41291. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41292. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41293. var vignettePower = -2.0 * this.vignetteWeight;
  41294. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41295. }
  41296. // Exposure
  41297. effect.setFloat("exposureLinear", this.exposure);
  41298. // Contrast
  41299. effect.setFloat("contrast", this.contrast);
  41300. // Color transform settings
  41301. if (this.colorGradingTexture) {
  41302. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41303. var textureSize = this.colorGradingTexture.getSize().height;
  41304. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41305. 0.5 / textureSize, // textureOffset
  41306. textureSize, // textureSize
  41307. this.colorGradingTexture.level // weight
  41308. );
  41309. }
  41310. };
  41311. /**
  41312. * Clones the current image processing instance.
  41313. * @return The cloned image processing
  41314. */
  41315. ImageProcessingConfiguration.prototype.clone = function () {
  41316. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41317. };
  41318. /**
  41319. * Serializes the current image processing instance to a json representation.
  41320. * @return a JSON representation
  41321. */
  41322. ImageProcessingConfiguration.prototype.serialize = function () {
  41323. return BABYLON.SerializationHelper.Serialize(this);
  41324. };
  41325. /**
  41326. * Parses the image processing from a json representation.
  41327. * @param source the JSON source to parse
  41328. * @return The parsed image processing
  41329. */
  41330. ImageProcessingConfiguration.Parse = function (source) {
  41331. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41332. };
  41333. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41334. /**
  41335. * Used to apply the vignette as a mix with the pixel color.
  41336. */
  41337. get: function () {
  41338. return this._VIGNETTEMODE_MULTIPLY;
  41339. },
  41340. enumerable: true,
  41341. configurable: true
  41342. });
  41343. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41344. /**
  41345. * Used to apply the vignette as a replacement of the pixel color.
  41346. */
  41347. get: function () {
  41348. return this._VIGNETTEMODE_OPAQUE;
  41349. },
  41350. enumerable: true,
  41351. configurable: true
  41352. });
  41353. // Static constants associated to the image processing.
  41354. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41355. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41356. __decorate([
  41357. BABYLON.serializeAsColorCurves()
  41358. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41359. __decorate([
  41360. BABYLON.serialize()
  41361. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41362. __decorate([
  41363. BABYLON.serializeAsTexture()
  41364. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41365. __decorate([
  41366. BABYLON.serialize()
  41367. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41368. __decorate([
  41369. BABYLON.serialize()
  41370. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41371. __decorate([
  41372. BABYLON.serialize()
  41373. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41374. __decorate([
  41375. BABYLON.serialize()
  41376. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41377. __decorate([
  41378. BABYLON.serialize()
  41379. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41380. __decorate([
  41381. BABYLON.serialize()
  41382. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41383. __decorate([
  41384. BABYLON.serialize()
  41385. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41386. __decorate([
  41387. BABYLON.serialize()
  41388. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41389. __decorate([
  41390. BABYLON.serialize()
  41391. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41392. __decorate([
  41393. BABYLON.serialize()
  41394. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41395. __decorate([
  41396. BABYLON.serializeAsColor4()
  41397. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41398. __decorate([
  41399. BABYLON.serialize()
  41400. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41401. __decorate([
  41402. BABYLON.serialize()
  41403. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41404. __decorate([
  41405. BABYLON.serialize()
  41406. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41407. __decorate([
  41408. BABYLON.serialize()
  41409. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41410. __decorate([
  41411. BABYLON.serialize()
  41412. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41413. return ImageProcessingConfiguration;
  41414. }());
  41415. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41416. })(BABYLON || (BABYLON = {}));
  41417. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41418. var BABYLON;
  41419. (function (BABYLON) {
  41420. /**
  41421. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41422. * It can help converting any input color in a desired output one. This can then be used to create effects
  41423. * from sepia, black and white to sixties or futuristic rendering...
  41424. *
  41425. * The only supported format is currently 3dl.
  41426. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41427. */
  41428. var ColorGradingTexture = /** @class */ (function (_super) {
  41429. __extends(ColorGradingTexture, _super);
  41430. /**
  41431. * Instantiates a ColorGradingTexture from the following parameters.
  41432. *
  41433. * @param url The location of the color gradind data (currently only supporting 3dl)
  41434. * @param scene The scene the texture will be used in
  41435. */
  41436. function ColorGradingTexture(url, scene) {
  41437. var _this = _super.call(this, scene) || this;
  41438. if (!url) {
  41439. return _this;
  41440. }
  41441. _this._engine = scene.getEngine();
  41442. _this._textureMatrix = BABYLON.Matrix.Identity();
  41443. _this.name = url;
  41444. _this.url = url;
  41445. _this.hasAlpha = false;
  41446. _this.isCube = false;
  41447. _this.is3D = _this._engine.webGLVersion > 1;
  41448. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41449. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41450. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41451. _this.anisotropicFilteringLevel = 1;
  41452. _this._texture = _this._getFromCache(url, true);
  41453. if (!_this._texture) {
  41454. if (!scene.useDelayedTextureLoading) {
  41455. _this.loadTexture();
  41456. }
  41457. else {
  41458. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41459. }
  41460. }
  41461. return _this;
  41462. }
  41463. /**
  41464. * Returns the texture matrix used in most of the material.
  41465. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41466. */
  41467. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41468. return this._textureMatrix;
  41469. };
  41470. /**
  41471. * Occurs when the file being loaded is a .3dl LUT file.
  41472. */
  41473. ColorGradingTexture.prototype.load3dlTexture = function () {
  41474. var engine = this._engine;
  41475. var texture;
  41476. if (engine.webGLVersion === 1) {
  41477. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41478. }
  41479. else {
  41480. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41481. }
  41482. this._texture = texture;
  41483. var callback = function (text) {
  41484. if (typeof text !== "string") {
  41485. return;
  41486. }
  41487. var data = null;
  41488. var tempData = null;
  41489. var line;
  41490. var lines = text.split('\n');
  41491. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41492. var maxColor = 0;
  41493. for (var i = 0; i < lines.length; i++) {
  41494. line = lines[i];
  41495. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41496. continue;
  41497. if (line.indexOf('#') === 0)
  41498. continue;
  41499. var words = line.split(" ");
  41500. if (size === 0) {
  41501. // Number of space + one
  41502. size = words.length;
  41503. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41504. tempData = new Float32Array(size * size * size * 4);
  41505. continue;
  41506. }
  41507. if (size != 0) {
  41508. var r = Math.max(parseInt(words[0]), 0);
  41509. var g = Math.max(parseInt(words[1]), 0);
  41510. var b = Math.max(parseInt(words[2]), 0);
  41511. maxColor = Math.max(r, maxColor);
  41512. maxColor = Math.max(g, maxColor);
  41513. maxColor = Math.max(b, maxColor);
  41514. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41515. if (tempData) {
  41516. tempData[pixelStorageIndex + 0] = r;
  41517. tempData[pixelStorageIndex + 1] = g;
  41518. tempData[pixelStorageIndex + 2] = b;
  41519. }
  41520. pixelIndexSlice++;
  41521. if (pixelIndexSlice % size == 0) {
  41522. pixelIndexH++;
  41523. pixelIndexSlice = 0;
  41524. if (pixelIndexH % size == 0) {
  41525. pixelIndexW++;
  41526. pixelIndexH = 0;
  41527. }
  41528. }
  41529. }
  41530. }
  41531. if (tempData && data) {
  41532. for (var i = 0; i < tempData.length; i++) {
  41533. if (i > 0 && (i + 1) % 4 === 0) {
  41534. data[i] = 255;
  41535. }
  41536. else {
  41537. var value = tempData[i];
  41538. data[i] = (value / maxColor * 255);
  41539. }
  41540. }
  41541. }
  41542. if (texture.is3D) {
  41543. texture.updateSize(size, size, size);
  41544. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41545. }
  41546. else {
  41547. texture.updateSize(size * size, size);
  41548. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41549. }
  41550. };
  41551. var scene = this.getScene();
  41552. if (scene) {
  41553. scene._loadFile(this.url, callback);
  41554. }
  41555. else {
  41556. this._engine._loadFile(this.url, callback);
  41557. }
  41558. return this._texture;
  41559. };
  41560. /**
  41561. * Starts the loading process of the texture.
  41562. */
  41563. ColorGradingTexture.prototype.loadTexture = function () {
  41564. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41565. this.load3dlTexture();
  41566. }
  41567. };
  41568. /**
  41569. * Clones the color gradind texture.
  41570. */
  41571. ColorGradingTexture.prototype.clone = function () {
  41572. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41573. // Base texture
  41574. newTexture.level = this.level;
  41575. return newTexture;
  41576. };
  41577. /**
  41578. * Called during delayed load for textures.
  41579. */
  41580. ColorGradingTexture.prototype.delayLoad = function () {
  41581. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41582. return;
  41583. }
  41584. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41585. this._texture = this._getFromCache(this.url, true);
  41586. if (!this._texture) {
  41587. this.loadTexture();
  41588. }
  41589. };
  41590. /**
  41591. * Parses a color grading texture serialized by Babylon.
  41592. * @param parsedTexture The texture information being parsedTexture
  41593. * @param scene The scene to load the texture in
  41594. * @param rootUrl The root url of the data assets to load
  41595. * @return A color gradind texture
  41596. */
  41597. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41598. var texture = null;
  41599. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41600. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41601. texture.name = parsedTexture.name;
  41602. texture.level = parsedTexture.level;
  41603. }
  41604. return texture;
  41605. };
  41606. /**
  41607. * Serializes the LUT texture to json format.
  41608. */
  41609. ColorGradingTexture.prototype.serialize = function () {
  41610. if (!this.name) {
  41611. return null;
  41612. }
  41613. var serializationObject = {};
  41614. serializationObject.name = this.name;
  41615. serializationObject.level = this.level;
  41616. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41617. return serializationObject;
  41618. };
  41619. /**
  41620. * Empty line regex stored for GC.
  41621. */
  41622. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41623. return ColorGradingTexture;
  41624. }(BABYLON.BaseTexture));
  41625. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41626. })(BABYLON || (BABYLON = {}));
  41627. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41628. var BABYLON;
  41629. (function (BABYLON) {
  41630. /**
  41631. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41632. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41633. * 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;
  41634. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41635. */
  41636. var ColorCurves = /** @class */ (function () {
  41637. function ColorCurves() {
  41638. this._dirty = true;
  41639. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41640. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41641. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41642. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41643. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41644. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41645. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41646. this._globalHue = 30;
  41647. this._globalDensity = 0;
  41648. this._globalSaturation = 0;
  41649. this._globalExposure = 0;
  41650. this._highlightsHue = 30;
  41651. this._highlightsDensity = 0;
  41652. this._highlightsSaturation = 0;
  41653. this._highlightsExposure = 0;
  41654. this._midtonesHue = 30;
  41655. this._midtonesDensity = 0;
  41656. this._midtonesSaturation = 0;
  41657. this._midtonesExposure = 0;
  41658. this._shadowsHue = 30;
  41659. this._shadowsDensity = 0;
  41660. this._shadowsSaturation = 0;
  41661. this._shadowsExposure = 0;
  41662. }
  41663. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41664. /**
  41665. * Gets the global Hue value.
  41666. * 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).
  41667. */
  41668. get: function () {
  41669. return this._globalHue;
  41670. },
  41671. /**
  41672. * Sets the global Hue value.
  41673. * 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).
  41674. */
  41675. set: function (value) {
  41676. this._globalHue = value;
  41677. this._dirty = true;
  41678. },
  41679. enumerable: true,
  41680. configurable: true
  41681. });
  41682. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41683. /**
  41684. * Gets the global Density value.
  41685. * 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.
  41686. * Values less than zero provide a filter of opposite hue.
  41687. */
  41688. get: function () {
  41689. return this._globalDensity;
  41690. },
  41691. /**
  41692. * Sets the global Density value.
  41693. * 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.
  41694. * Values less than zero provide a filter of opposite hue.
  41695. */
  41696. set: function (value) {
  41697. this._globalDensity = value;
  41698. this._dirty = true;
  41699. },
  41700. enumerable: true,
  41701. configurable: true
  41702. });
  41703. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41704. /**
  41705. * Gets the global Saturation value.
  41706. * 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.
  41707. */
  41708. get: function () {
  41709. return this._globalSaturation;
  41710. },
  41711. /**
  41712. * Sets the global Saturation value.
  41713. * 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.
  41714. */
  41715. set: function (value) {
  41716. this._globalSaturation = value;
  41717. this._dirty = true;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41723. /**
  41724. * Gets the highlights Hue value.
  41725. * 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).
  41726. */
  41727. get: function () {
  41728. return this._highlightsHue;
  41729. },
  41730. /**
  41731. * Sets the highlights Hue value.
  41732. * 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).
  41733. */
  41734. set: function (value) {
  41735. this._highlightsHue = value;
  41736. this._dirty = true;
  41737. },
  41738. enumerable: true,
  41739. configurable: true
  41740. });
  41741. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41742. /**
  41743. * Gets the highlights Density value.
  41744. * 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.
  41745. * Values less than zero provide a filter of opposite hue.
  41746. */
  41747. get: function () {
  41748. return this._highlightsDensity;
  41749. },
  41750. /**
  41751. * Sets the highlights Density value.
  41752. * 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.
  41753. * Values less than zero provide a filter of opposite hue.
  41754. */
  41755. set: function (value) {
  41756. this._highlightsDensity = value;
  41757. this._dirty = true;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41763. /**
  41764. * Gets the highlights Saturation value.
  41765. * 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.
  41766. */
  41767. get: function () {
  41768. return this._highlightsSaturation;
  41769. },
  41770. /**
  41771. * Sets the highlights Saturation value.
  41772. * 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.
  41773. */
  41774. set: function (value) {
  41775. this._highlightsSaturation = value;
  41776. this._dirty = true;
  41777. },
  41778. enumerable: true,
  41779. configurable: true
  41780. });
  41781. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41782. /**
  41783. * Gets the highlights Exposure value.
  41784. * 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.
  41785. */
  41786. get: function () {
  41787. return this._highlightsExposure;
  41788. },
  41789. /**
  41790. * Sets the highlights Exposure value.
  41791. * 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.
  41792. */
  41793. set: function (value) {
  41794. this._highlightsExposure = value;
  41795. this._dirty = true;
  41796. },
  41797. enumerable: true,
  41798. configurable: true
  41799. });
  41800. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41801. /**
  41802. * Gets the midtones Hue value.
  41803. * 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).
  41804. */
  41805. get: function () {
  41806. return this._midtonesHue;
  41807. },
  41808. /**
  41809. * Sets the midtones Hue value.
  41810. * 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).
  41811. */
  41812. set: function (value) {
  41813. this._midtonesHue = value;
  41814. this._dirty = true;
  41815. },
  41816. enumerable: true,
  41817. configurable: true
  41818. });
  41819. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41820. /**
  41821. * Gets the midtones Density value.
  41822. * 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.
  41823. * Values less than zero provide a filter of opposite hue.
  41824. */
  41825. get: function () {
  41826. return this._midtonesDensity;
  41827. },
  41828. /**
  41829. * Sets the midtones Density value.
  41830. * 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.
  41831. * Values less than zero provide a filter of opposite hue.
  41832. */
  41833. set: function (value) {
  41834. this._midtonesDensity = value;
  41835. this._dirty = true;
  41836. },
  41837. enumerable: true,
  41838. configurable: true
  41839. });
  41840. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41841. /**
  41842. * Gets the midtones Saturation value.
  41843. * 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.
  41844. */
  41845. get: function () {
  41846. return this._midtonesSaturation;
  41847. },
  41848. /**
  41849. * Sets the midtones Saturation value.
  41850. * 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.
  41851. */
  41852. set: function (value) {
  41853. this._midtonesSaturation = value;
  41854. this._dirty = true;
  41855. },
  41856. enumerable: true,
  41857. configurable: true
  41858. });
  41859. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41860. /**
  41861. * Gets the midtones Exposure value.
  41862. * 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.
  41863. */
  41864. get: function () {
  41865. return this._midtonesExposure;
  41866. },
  41867. /**
  41868. * Sets the midtones Exposure value.
  41869. * 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.
  41870. */
  41871. set: function (value) {
  41872. this._midtonesExposure = value;
  41873. this._dirty = true;
  41874. },
  41875. enumerable: true,
  41876. configurable: true
  41877. });
  41878. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41879. /**
  41880. * Gets the shadows Hue value.
  41881. * 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).
  41882. */
  41883. get: function () {
  41884. return this._shadowsHue;
  41885. },
  41886. /**
  41887. * Sets the shadows Hue value.
  41888. * 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).
  41889. */
  41890. set: function (value) {
  41891. this._shadowsHue = value;
  41892. this._dirty = true;
  41893. },
  41894. enumerable: true,
  41895. configurable: true
  41896. });
  41897. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41898. /**
  41899. * Gets the shadows Density value.
  41900. * 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.
  41901. * Values less than zero provide a filter of opposite hue.
  41902. */
  41903. get: function () {
  41904. return this._shadowsDensity;
  41905. },
  41906. /**
  41907. * Sets the shadows Density value.
  41908. * 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.
  41909. * Values less than zero provide a filter of opposite hue.
  41910. */
  41911. set: function (value) {
  41912. this._shadowsDensity = value;
  41913. this._dirty = true;
  41914. },
  41915. enumerable: true,
  41916. configurable: true
  41917. });
  41918. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41919. /**
  41920. * Gets the shadows Saturation value.
  41921. * 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.
  41922. */
  41923. get: function () {
  41924. return this._shadowsSaturation;
  41925. },
  41926. /**
  41927. * Sets the shadows Saturation value.
  41928. * 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.
  41929. */
  41930. set: function (value) {
  41931. this._shadowsSaturation = value;
  41932. this._dirty = true;
  41933. },
  41934. enumerable: true,
  41935. configurable: true
  41936. });
  41937. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41938. /**
  41939. * Gets the shadows Exposure value.
  41940. * 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.
  41941. */
  41942. get: function () {
  41943. return this._shadowsExposure;
  41944. },
  41945. /**
  41946. * Sets the shadows Exposure value.
  41947. * 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.
  41948. */
  41949. set: function (value) {
  41950. this._shadowsExposure = value;
  41951. this._dirty = true;
  41952. },
  41953. enumerable: true,
  41954. configurable: true
  41955. });
  41956. ColorCurves.prototype.getClassName = function () {
  41957. return "ColorCurves";
  41958. };
  41959. /**
  41960. * Binds the color curves to the shader.
  41961. * @param colorCurves The color curve to bind
  41962. * @param effect The effect to bind to
  41963. */
  41964. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41965. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41966. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41967. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41968. if (colorCurves._dirty) {
  41969. colorCurves._dirty = false;
  41970. // Fill in global info.
  41971. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41972. // Compute highlights info.
  41973. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41974. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41975. // Compute midtones info.
  41976. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41977. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41978. // Compute shadows info.
  41979. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41980. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41981. // Compute deltas (neutral is midtones).
  41982. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41983. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41984. }
  41985. if (effect) {
  41986. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41987. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41988. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41989. }
  41990. };
  41991. /**
  41992. * Prepare the list of uniforms associated with the ColorCurves effects.
  41993. * @param uniformsList The list of uniforms used in the effect
  41994. */
  41995. ColorCurves.PrepareUniforms = function (uniformsList) {
  41996. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41997. };
  41998. /**
  41999. * Returns color grading data based on a hue, density, saturation and exposure value.
  42000. * @param filterHue The hue of the color filter.
  42001. * @param filterDensity The density of the color filter.
  42002. * @param saturation The saturation.
  42003. * @param exposure The exposure.
  42004. * @param result The result data container.
  42005. */
  42006. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42007. if (hue == null) {
  42008. return;
  42009. }
  42010. hue = ColorCurves.clamp(hue, 0, 360);
  42011. density = ColorCurves.clamp(density, -100, 100);
  42012. saturation = ColorCurves.clamp(saturation, -100, 100);
  42013. exposure = ColorCurves.clamp(exposure, -100, 100);
  42014. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42015. // so that the maximum filter density is only 50% control. This provides fine control
  42016. // for small values and reasonable range.
  42017. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42018. density *= 0.5;
  42019. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42020. if (density < 0) {
  42021. density *= -1;
  42022. hue = (hue + 180) % 360;
  42023. }
  42024. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42025. result.scaleToRef(2, result);
  42026. result.a = 1 + 0.01 * saturation;
  42027. };
  42028. /**
  42029. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42030. * @param value The input slider value in range [-100,100].
  42031. * @returns Adjusted value.
  42032. */
  42033. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42034. value /= 100;
  42035. var x = Math.abs(value);
  42036. x = Math.pow(x, 2);
  42037. if (value < 0) {
  42038. x *= -1;
  42039. }
  42040. x *= 100;
  42041. return x;
  42042. };
  42043. /**
  42044. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42045. * @param hue The hue (H) input.
  42046. * @param saturation The saturation (S) input.
  42047. * @param brightness The brightness (B) input.
  42048. * @result An RGBA color represented as Vector4.
  42049. */
  42050. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42051. var h = ColorCurves.clamp(hue, 0, 360);
  42052. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42053. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42054. if (s === 0) {
  42055. result.r = v;
  42056. result.g = v;
  42057. result.b = v;
  42058. }
  42059. else {
  42060. // sector 0 to 5
  42061. h /= 60;
  42062. var i = Math.floor(h);
  42063. // fractional part of h
  42064. var f = h - i;
  42065. var p = v * (1 - s);
  42066. var q = v * (1 - s * f);
  42067. var t = v * (1 - s * (1 - f));
  42068. switch (i) {
  42069. case 0:
  42070. result.r = v;
  42071. result.g = t;
  42072. result.b = p;
  42073. break;
  42074. case 1:
  42075. result.r = q;
  42076. result.g = v;
  42077. result.b = p;
  42078. break;
  42079. case 2:
  42080. result.r = p;
  42081. result.g = v;
  42082. result.b = t;
  42083. break;
  42084. case 3:
  42085. result.r = p;
  42086. result.g = q;
  42087. result.b = v;
  42088. break;
  42089. case 4:
  42090. result.r = t;
  42091. result.g = p;
  42092. result.b = v;
  42093. break;
  42094. default: // case 5:
  42095. result.r = v;
  42096. result.g = p;
  42097. result.b = q;
  42098. break;
  42099. }
  42100. }
  42101. result.a = 1;
  42102. };
  42103. /**
  42104. * Returns a value clamped between min and max
  42105. * @param value The value to clamp
  42106. * @param min The minimum of value
  42107. * @param max The maximum of value
  42108. * @returns The clamped value.
  42109. */
  42110. ColorCurves.clamp = function (value, min, max) {
  42111. return Math.min(Math.max(value, min), max);
  42112. };
  42113. /**
  42114. * Clones the current color curve instance.
  42115. * @return The cloned curves
  42116. */
  42117. ColorCurves.prototype.clone = function () {
  42118. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42119. };
  42120. /**
  42121. * Serializes the current color curve instance to a json representation.
  42122. * @return a JSON representation
  42123. */
  42124. ColorCurves.prototype.serialize = function () {
  42125. return BABYLON.SerializationHelper.Serialize(this);
  42126. };
  42127. /**
  42128. * Parses the color curve from a json representation.
  42129. * @param source the JSON source to parse
  42130. * @return The parsed curves
  42131. */
  42132. ColorCurves.Parse = function (source) {
  42133. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42134. };
  42135. __decorate([
  42136. BABYLON.serialize()
  42137. ], ColorCurves.prototype, "_globalHue", void 0);
  42138. __decorate([
  42139. BABYLON.serialize()
  42140. ], ColorCurves.prototype, "_globalDensity", void 0);
  42141. __decorate([
  42142. BABYLON.serialize()
  42143. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42144. __decorate([
  42145. BABYLON.serialize()
  42146. ], ColorCurves.prototype, "_globalExposure", void 0);
  42147. __decorate([
  42148. BABYLON.serialize()
  42149. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42150. __decorate([
  42151. BABYLON.serialize()
  42152. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42153. __decorate([
  42154. BABYLON.serialize()
  42155. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42156. __decorate([
  42157. BABYLON.serialize()
  42158. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42159. __decorate([
  42160. BABYLON.serialize()
  42161. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42162. __decorate([
  42163. BABYLON.serialize()
  42164. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42165. __decorate([
  42166. BABYLON.serialize()
  42167. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42168. __decorate([
  42169. BABYLON.serialize()
  42170. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42171. return ColorCurves;
  42172. }());
  42173. BABYLON.ColorCurves = ColorCurves;
  42174. })(BABYLON || (BABYLON = {}));
  42175. //# sourceMappingURL=babylon.colorCurves.js.map
  42176. //# sourceMappingURL=babylon.behavior.js.map
  42177. var BABYLON;
  42178. (function (BABYLON) {
  42179. /**
  42180. * "Static Class" containing the most commonly used helper while dealing with material for
  42181. * rendering purpose.
  42182. *
  42183. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42184. *
  42185. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42186. */
  42187. var MaterialHelper = /** @class */ (function () {
  42188. function MaterialHelper() {
  42189. }
  42190. /**
  42191. * Bind the current view position to an effect.
  42192. * @param effect The effect to be bound
  42193. * @param scene The scene the eyes position is used from
  42194. */
  42195. MaterialHelper.BindEyePosition = function (effect, scene) {
  42196. if (scene._forcedViewPosition) {
  42197. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42198. return;
  42199. }
  42200. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42201. };
  42202. /**
  42203. * Helps preparing the defines values about the UVs in used in the effect.
  42204. * UVs are shared as much as we can accross chanels in the shaders.
  42205. * @param texture The texture we are preparing the UVs for
  42206. * @param defines The defines to update
  42207. * @param key The chanel key "diffuse", "specular"... used in the shader
  42208. */
  42209. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42210. defines._needUVs = true;
  42211. defines[key] = true;
  42212. if (texture.getTextureMatrix().isIdentity(true)) {
  42213. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42214. if (texture.coordinatesIndex === 0) {
  42215. defines["MAINUV1"] = true;
  42216. }
  42217. else {
  42218. defines["MAINUV2"] = true;
  42219. }
  42220. }
  42221. else {
  42222. defines[key + "DIRECTUV"] = 0;
  42223. }
  42224. };
  42225. /**
  42226. * Binds a texture matrix value to its corrsponding uniform
  42227. * @param texture The texture to bind the matrix for
  42228. * @param uniformBuffer The uniform buffer receivin the data
  42229. * @param key The chanel key "diffuse", "specular"... used in the shader
  42230. */
  42231. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42232. var matrix = texture.getTextureMatrix();
  42233. if (!matrix.isIdentity(true)) {
  42234. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42235. }
  42236. };
  42237. /**
  42238. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42239. * @param mesh defines the current mesh
  42240. * @param scene defines the current scene
  42241. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42242. * @param pointsCloud defines if point cloud rendering has to be turned on
  42243. * @param fogEnabled defines if fog has to be turned on
  42244. * @param alphaTest defines if alpha testing has to be turned on
  42245. * @param defines defines the current list of defines
  42246. */
  42247. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42248. if (defines._areMiscDirty) {
  42249. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42250. defines["POINTSIZE"] = pointsCloud;
  42251. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42252. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42253. defines["ALPHATEST"] = alphaTest;
  42254. }
  42255. };
  42256. /**
  42257. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42258. * @param scene defines the current scene
  42259. * @param engine defines the current engine
  42260. * @param defines specifies the list of active defines
  42261. * @param useInstances defines if instances have to be turned on
  42262. * @param useClipPlane defines if clip plane have to be turned on
  42263. */
  42264. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42265. if (useClipPlane === void 0) { useClipPlane = null; }
  42266. var changed = false;
  42267. if (useClipPlane == null) {
  42268. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42269. }
  42270. if (defines["CLIPPLANE"] !== useClipPlane) {
  42271. defines["CLIPPLANE"] = useClipPlane;
  42272. changed = true;
  42273. }
  42274. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42275. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42276. changed = true;
  42277. }
  42278. if (defines["INSTANCES"] !== useInstances) {
  42279. defines["INSTANCES"] = useInstances;
  42280. changed = true;
  42281. }
  42282. if (changed) {
  42283. defines.markAsUnprocessed();
  42284. }
  42285. };
  42286. /**
  42287. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42288. * @param mesh The mesh containing the geometry data we will draw
  42289. * @param defines The defines to update
  42290. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42291. * @param useBones Precise whether bones should be used or not (override mesh info)
  42292. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42293. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42294. * @returns false if defines are considered not dirty and have not been checked
  42295. */
  42296. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42297. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42298. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42299. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42300. return false;
  42301. }
  42302. defines._normals = defines._needNormals;
  42303. defines._uvs = defines._needUVs;
  42304. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42305. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42306. defines["TANGENT"] = true;
  42307. }
  42308. if (defines._needUVs) {
  42309. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42310. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42311. }
  42312. else {
  42313. defines["UV1"] = false;
  42314. defines["UV2"] = false;
  42315. }
  42316. if (useVertexColor) {
  42317. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42318. defines["VERTEXCOLOR"] = hasVertexColors;
  42319. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42320. }
  42321. if (useBones) {
  42322. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42323. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42324. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42325. }
  42326. else {
  42327. defines["NUM_BONE_INFLUENCERS"] = 0;
  42328. defines["BonesPerMesh"] = 0;
  42329. }
  42330. }
  42331. if (useMorphTargets) {
  42332. var manager = mesh.morphTargetManager;
  42333. if (manager) {
  42334. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42335. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42336. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42337. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42338. }
  42339. else {
  42340. defines["MORPHTARGETS_TANGENT"] = false;
  42341. defines["MORPHTARGETS_NORMAL"] = false;
  42342. defines["MORPHTARGETS"] = false;
  42343. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42344. }
  42345. }
  42346. return true;
  42347. };
  42348. /**
  42349. * Prepares the defines related to the light information passed in parameter
  42350. * @param scene The scene we are intending to draw
  42351. * @param mesh The mesh the effect is compiling for
  42352. * @param defines The defines to update
  42353. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42354. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42355. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42356. * @returns true if normals will be required for the rest of the effect
  42357. */
  42358. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42359. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42360. if (disableLighting === void 0) { disableLighting = false; }
  42361. if (!defines._areLightsDirty) {
  42362. return defines._needNormals;
  42363. }
  42364. var lightIndex = 0;
  42365. var needNormals = false;
  42366. var needRebuild = false;
  42367. var lightmapMode = false;
  42368. var shadowEnabled = false;
  42369. var specularEnabled = false;
  42370. if (scene.lightsEnabled && !disableLighting) {
  42371. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42372. var light = _a[_i];
  42373. needNormals = true;
  42374. if (defines["LIGHT" + lightIndex] === undefined) {
  42375. needRebuild = true;
  42376. }
  42377. defines["LIGHT" + lightIndex] = true;
  42378. defines["SPOTLIGHT" + lightIndex] = false;
  42379. defines["HEMILIGHT" + lightIndex] = false;
  42380. defines["POINTLIGHT" + lightIndex] = false;
  42381. defines["DIRLIGHT" + lightIndex] = false;
  42382. var type;
  42383. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42384. type = "SPOTLIGHT" + lightIndex;
  42385. var spotLight = light;
  42386. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42387. }
  42388. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42389. type = "HEMILIGHT" + lightIndex;
  42390. }
  42391. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42392. type = "POINTLIGHT" + lightIndex;
  42393. }
  42394. else {
  42395. type = "DIRLIGHT" + lightIndex;
  42396. }
  42397. defines[type] = true;
  42398. // Specular
  42399. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42400. specularEnabled = true;
  42401. }
  42402. // Shadows
  42403. defines["SHADOW" + lightIndex] = false;
  42404. defines["SHADOWPCF" + lightIndex] = false;
  42405. defines["SHADOWPCSS" + lightIndex] = false;
  42406. defines["SHADOWPOISSON" + lightIndex] = false;
  42407. defines["SHADOWESM" + lightIndex] = false;
  42408. defines["SHADOWCUBE" + lightIndex] = false;
  42409. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42410. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42411. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42412. var shadowGenerator = light.getShadowGenerator();
  42413. if (shadowGenerator) {
  42414. shadowEnabled = true;
  42415. shadowGenerator.prepareDefines(defines, lightIndex);
  42416. }
  42417. }
  42418. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42419. lightmapMode = true;
  42420. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42421. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42422. }
  42423. else {
  42424. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42425. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42426. }
  42427. lightIndex++;
  42428. if (lightIndex === maxSimultaneousLights)
  42429. break;
  42430. }
  42431. }
  42432. defines["SPECULARTERM"] = specularEnabled;
  42433. defines["SHADOWS"] = shadowEnabled;
  42434. // Resetting all other lights if any
  42435. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42436. if (defines["LIGHT" + index] !== undefined) {
  42437. defines["LIGHT" + index] = false;
  42438. defines["HEMILIGHT" + lightIndex] = false;
  42439. defines["POINTLIGHT" + lightIndex] = false;
  42440. defines["DIRLIGHT" + lightIndex] = false;
  42441. defines["SPOTLIGHT" + lightIndex] = false;
  42442. defines["SHADOW" + lightIndex] = false;
  42443. }
  42444. }
  42445. var caps = scene.getEngine().getCaps();
  42446. if (defines["SHADOWFLOAT"] === undefined) {
  42447. needRebuild = true;
  42448. }
  42449. defines["SHADOWFLOAT"] = shadowEnabled &&
  42450. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42451. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42452. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42453. if (needRebuild) {
  42454. defines.rebuild();
  42455. }
  42456. return needNormals;
  42457. };
  42458. /**
  42459. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42460. * that won t be acctive due to defines being turned off.
  42461. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42462. * @param samplersList The samplers list
  42463. * @param defines The defines helping in the list generation
  42464. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42465. */
  42466. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42467. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42468. var uniformsList;
  42469. var uniformBuffersList = null;
  42470. if (uniformsListOrOptions.uniformsNames) {
  42471. var options = uniformsListOrOptions;
  42472. uniformsList = options.uniformsNames;
  42473. uniformBuffersList = options.uniformBuffersNames;
  42474. samplersList = options.samplers;
  42475. defines = options.defines;
  42476. maxSimultaneousLights = options.maxSimultaneousLights;
  42477. }
  42478. else {
  42479. uniformsList = uniformsListOrOptions;
  42480. if (!samplersList) {
  42481. samplersList = [];
  42482. }
  42483. }
  42484. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42485. if (!defines["LIGHT" + lightIndex]) {
  42486. break;
  42487. }
  42488. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42489. if (uniformBuffersList) {
  42490. uniformBuffersList.push("Light" + lightIndex);
  42491. }
  42492. samplersList.push("shadowSampler" + lightIndex);
  42493. samplersList.push("depthSampler" + lightIndex);
  42494. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42495. samplersList.push("projectionLightSampler" + lightIndex);
  42496. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42497. }
  42498. }
  42499. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42500. uniformsList.push("morphTargetInfluences");
  42501. }
  42502. };
  42503. /**
  42504. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42505. * @param defines The defines to update while falling back
  42506. * @param fallbacks The authorized effect fallbacks
  42507. * @param maxSimultaneousLights The maximum number of lights allowed
  42508. * @param rank the current rank of the Effect
  42509. * @returns The newly affected rank
  42510. */
  42511. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42512. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42513. if (rank === void 0) { rank = 0; }
  42514. var lightFallbackRank = 0;
  42515. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42516. if (!defines["LIGHT" + lightIndex]) {
  42517. break;
  42518. }
  42519. if (lightIndex > 0) {
  42520. lightFallbackRank = rank + lightIndex;
  42521. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42522. }
  42523. if (!defines["SHADOWS"]) {
  42524. if (defines["SHADOW" + lightIndex]) {
  42525. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42526. }
  42527. if (defines["SHADOWPCF" + lightIndex]) {
  42528. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42529. }
  42530. if (defines["SHADOWPCSS" + lightIndex]) {
  42531. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42532. }
  42533. if (defines["SHADOWPOISSON" + lightIndex]) {
  42534. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42535. }
  42536. if (defines["SHADOWESM" + lightIndex]) {
  42537. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42538. }
  42539. }
  42540. }
  42541. return lightFallbackRank++;
  42542. };
  42543. /**
  42544. * Prepares the list of attributes required for morph targets according to the effect defines.
  42545. * @param attribs The current list of supported attribs
  42546. * @param mesh The mesh to prepare the morph targets attributes for
  42547. * @param defines The current Defines of the effect
  42548. */
  42549. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42550. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42551. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42552. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42553. var manager = mesh.morphTargetManager;
  42554. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42555. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42556. for (var index = 0; index < influencers; index++) {
  42557. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42558. if (normal) {
  42559. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42560. }
  42561. if (tangent) {
  42562. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42563. }
  42564. if (attribs.length > maxAttributesCount) {
  42565. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42566. }
  42567. }
  42568. }
  42569. };
  42570. /**
  42571. * Prepares the list of attributes required for bones according to the effect defines.
  42572. * @param attribs The current list of supported attribs
  42573. * @param mesh The mesh to prepare the bones attributes for
  42574. * @param defines The current Defines of the effect
  42575. * @param fallbacks The current efffect fallback strategy
  42576. */
  42577. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42578. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42579. fallbacks.addCPUSkinningFallback(0, mesh);
  42580. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42581. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42582. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42583. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42584. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42585. }
  42586. }
  42587. };
  42588. /**
  42589. * Prepares the list of attributes required for instances according to the effect defines.
  42590. * @param attribs The current list of supported attribs
  42591. * @param defines The current Defines of the effect
  42592. */
  42593. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42594. if (defines["INSTANCES"]) {
  42595. attribs.push("world0");
  42596. attribs.push("world1");
  42597. attribs.push("world2");
  42598. attribs.push("world3");
  42599. }
  42600. };
  42601. /**
  42602. * Binds the light shadow information to the effect for the given mesh.
  42603. * @param light The light containing the generator
  42604. * @param scene The scene the lights belongs to
  42605. * @param mesh The mesh we are binding the information to render
  42606. * @param lightIndex The light index in the effect used to render the mesh
  42607. * @param effect The effect we are binding the data to
  42608. */
  42609. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42610. if (light.shadowEnabled && mesh.receiveShadows) {
  42611. var shadowGenerator = light.getShadowGenerator();
  42612. if (shadowGenerator) {
  42613. shadowGenerator.bindShadowLight(lightIndex, effect);
  42614. }
  42615. }
  42616. };
  42617. /**
  42618. * Binds the light information to the effect.
  42619. * @param light The light containing the generator
  42620. * @param effect The effect we are binding the data to
  42621. * @param lightIndex The light index in the effect used to render
  42622. */
  42623. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42624. light.transferToEffect(effect, lightIndex + "");
  42625. };
  42626. /**
  42627. * Binds the lights information from the scene to the effect for the given mesh.
  42628. * @param scene The scene the lights belongs to
  42629. * @param mesh The mesh we are binding the information to render
  42630. * @param effect The effect we are binding the data to
  42631. * @param defines The generated defines for the effect
  42632. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42633. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42634. */
  42635. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42636. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42637. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42638. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42639. for (var i = 0; i < len; i++) {
  42640. var light = mesh._lightSources[i];
  42641. var iAsString = i.toString();
  42642. var scaledIntensity = light.getScaledIntensity();
  42643. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42644. MaterialHelper.BindLightProperties(light, effect, i);
  42645. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42646. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42647. if (defines["SPECULARTERM"]) {
  42648. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42649. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42650. }
  42651. // Shadows
  42652. if (scene.shadowsEnabled) {
  42653. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42654. }
  42655. light._uniformBuffer.update();
  42656. }
  42657. };
  42658. /**
  42659. * Binds the fog information from the scene to the effect for the given mesh.
  42660. * @param scene The scene the lights belongs to
  42661. * @param mesh The mesh we are binding the information to render
  42662. * @param effect The effect we are binding the data to
  42663. */
  42664. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42665. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42666. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42667. effect.setColor3("vFogColor", scene.fogColor);
  42668. }
  42669. };
  42670. /**
  42671. * Binds the bones information from the mesh to the effect.
  42672. * @param mesh The mesh we are binding the information to render
  42673. * @param effect The effect we are binding the data to
  42674. */
  42675. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42676. if (!effect || !mesh) {
  42677. return;
  42678. }
  42679. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42680. mesh.computeBonesUsingShaders = false;
  42681. }
  42682. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42683. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42684. if (matrices) {
  42685. effect.setMatrices("mBones", matrices);
  42686. }
  42687. }
  42688. };
  42689. /**
  42690. * Binds the morph targets information from the mesh to the effect.
  42691. * @param abstractMesh The mesh we are binding the information to render
  42692. * @param effect The effect we are binding the data to
  42693. */
  42694. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42695. var manager = abstractMesh.morphTargetManager;
  42696. if (!abstractMesh || !manager) {
  42697. return;
  42698. }
  42699. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42700. };
  42701. /**
  42702. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42703. * @param defines The generated defines used in the effect
  42704. * @param effect The effect we are binding the data to
  42705. * @param scene The scene we are willing to render with logarithmic scale for
  42706. */
  42707. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42708. if (defines["LOGARITHMICDEPTH"]) {
  42709. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42710. }
  42711. };
  42712. /**
  42713. * Binds the clip plane information from the scene to the effect.
  42714. * @param scene The scene the clip plane information are extracted from
  42715. * @param effect The effect we are binding the data to
  42716. */
  42717. MaterialHelper.BindClipPlane = function (effect, scene) {
  42718. if (scene.clipPlane) {
  42719. var clipPlane = scene.clipPlane;
  42720. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42721. }
  42722. };
  42723. return MaterialHelper;
  42724. }());
  42725. BABYLON.MaterialHelper = MaterialHelper;
  42726. })(BABYLON || (BABYLON = {}));
  42727. //# sourceMappingURL=babylon.materialHelper.js.map
  42728. var BABYLON;
  42729. (function (BABYLON) {
  42730. var PushMaterial = /** @class */ (function (_super) {
  42731. __extends(PushMaterial, _super);
  42732. function PushMaterial(name, scene) {
  42733. var _this = _super.call(this, name, scene) || this;
  42734. _this._normalMatrix = new BABYLON.Matrix();
  42735. _this.storeEffectOnSubMeshes = true;
  42736. return _this;
  42737. }
  42738. PushMaterial.prototype.getEffect = function () {
  42739. return this._activeEffect;
  42740. };
  42741. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42742. if (!mesh) {
  42743. return false;
  42744. }
  42745. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42746. return true;
  42747. }
  42748. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42749. };
  42750. /**
  42751. * Binds the given world matrix to the active effect
  42752. *
  42753. * @param world the matrix to bind
  42754. */
  42755. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42756. this._activeEffect.setMatrix("world", world);
  42757. };
  42758. /**
  42759. * Binds the given normal matrix to the active effect
  42760. *
  42761. * @param normalMatrix the matrix to bind
  42762. */
  42763. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42764. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42765. };
  42766. PushMaterial.prototype.bind = function (world, mesh) {
  42767. if (!mesh) {
  42768. return;
  42769. }
  42770. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42771. };
  42772. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42773. if (effect === void 0) { effect = null; }
  42774. _super.prototype._afterBind.call(this, mesh);
  42775. this.getScene()._cachedEffect = effect;
  42776. };
  42777. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42778. if (visibility === void 0) { visibility = 1; }
  42779. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42780. };
  42781. return PushMaterial;
  42782. }(BABYLON.Material));
  42783. BABYLON.PushMaterial = PushMaterial;
  42784. })(BABYLON || (BABYLON = {}));
  42785. //# sourceMappingURL=babylon.pushMaterial.js.map
  42786. var BABYLON;
  42787. (function (BABYLON) {
  42788. /** @hidden */
  42789. var StandardMaterialDefines = /** @class */ (function (_super) {
  42790. __extends(StandardMaterialDefines, _super);
  42791. function StandardMaterialDefines() {
  42792. var _this = _super.call(this) || this;
  42793. _this.MAINUV1 = false;
  42794. _this.MAINUV2 = false;
  42795. _this.DIFFUSE = false;
  42796. _this.DIFFUSEDIRECTUV = 0;
  42797. _this.AMBIENT = false;
  42798. _this.AMBIENTDIRECTUV = 0;
  42799. _this.OPACITY = false;
  42800. _this.OPACITYDIRECTUV = 0;
  42801. _this.OPACITYRGB = false;
  42802. _this.REFLECTION = false;
  42803. _this.EMISSIVE = false;
  42804. _this.EMISSIVEDIRECTUV = 0;
  42805. _this.SPECULAR = false;
  42806. _this.SPECULARDIRECTUV = 0;
  42807. _this.BUMP = false;
  42808. _this.BUMPDIRECTUV = 0;
  42809. _this.PARALLAX = false;
  42810. _this.PARALLAXOCCLUSION = false;
  42811. _this.SPECULAROVERALPHA = false;
  42812. _this.CLIPPLANE = false;
  42813. _this.ALPHATEST = false;
  42814. _this.DEPTHPREPASS = false;
  42815. _this.ALPHAFROMDIFFUSE = false;
  42816. _this.POINTSIZE = false;
  42817. _this.FOG = false;
  42818. _this.SPECULARTERM = false;
  42819. _this.DIFFUSEFRESNEL = false;
  42820. _this.OPACITYFRESNEL = false;
  42821. _this.REFLECTIONFRESNEL = false;
  42822. _this.REFRACTIONFRESNEL = false;
  42823. _this.EMISSIVEFRESNEL = false;
  42824. _this.FRESNEL = false;
  42825. _this.NORMAL = false;
  42826. _this.UV1 = false;
  42827. _this.UV2 = false;
  42828. _this.VERTEXCOLOR = false;
  42829. _this.VERTEXALPHA = false;
  42830. _this.NUM_BONE_INFLUENCERS = 0;
  42831. _this.BonesPerMesh = 0;
  42832. _this.INSTANCES = false;
  42833. _this.GLOSSINESS = false;
  42834. _this.ROUGHNESS = false;
  42835. _this.EMISSIVEASILLUMINATION = false;
  42836. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42837. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42838. _this.LIGHTMAP = false;
  42839. _this.LIGHTMAPDIRECTUV = 0;
  42840. _this.OBJECTSPACE_NORMALMAP = false;
  42841. _this.USELIGHTMAPASSHADOWMAP = false;
  42842. _this.REFLECTIONMAP_3D = false;
  42843. _this.REFLECTIONMAP_SPHERICAL = false;
  42844. _this.REFLECTIONMAP_PLANAR = false;
  42845. _this.REFLECTIONMAP_CUBIC = false;
  42846. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42847. _this.REFLECTIONMAP_PROJECTION = false;
  42848. _this.REFLECTIONMAP_SKYBOX = false;
  42849. _this.REFLECTIONMAP_EXPLICIT = false;
  42850. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42851. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42852. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42853. _this.INVERTCUBICMAP = false;
  42854. _this.LOGARITHMICDEPTH = false;
  42855. _this.REFRACTION = false;
  42856. _this.REFRACTIONMAP_3D = false;
  42857. _this.REFLECTIONOVERALPHA = false;
  42858. _this.TWOSIDEDLIGHTING = false;
  42859. _this.SHADOWFLOAT = false;
  42860. _this.MORPHTARGETS = false;
  42861. _this.MORPHTARGETS_NORMAL = false;
  42862. _this.MORPHTARGETS_TANGENT = false;
  42863. _this.NUM_MORPH_INFLUENCERS = 0;
  42864. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42865. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42866. _this.IMAGEPROCESSING = false;
  42867. _this.VIGNETTE = false;
  42868. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42869. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42870. _this.TONEMAPPING = false;
  42871. _this.CONTRAST = false;
  42872. _this.COLORCURVES = false;
  42873. _this.COLORGRADING = false;
  42874. _this.COLORGRADING3D = false;
  42875. _this.SAMPLER3DGREENDEPTH = false;
  42876. _this.SAMPLER3DBGRMAP = false;
  42877. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42878. /**
  42879. * If the reflection texture on this material is in linear color space
  42880. * @hidden
  42881. */
  42882. _this.IS_REFLECTION_LINEAR = false;
  42883. /**
  42884. * If the refraction texture on this material is in linear color space
  42885. * @hidden
  42886. */
  42887. _this.IS_REFRACTION_LINEAR = false;
  42888. _this.EXPOSURE = false;
  42889. _this.rebuild();
  42890. return _this;
  42891. }
  42892. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42893. var modes = [
  42894. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42895. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42896. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42897. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42898. ];
  42899. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42900. var mode = modes_1[_i];
  42901. this[mode] = (mode === modeToEnable);
  42902. }
  42903. };
  42904. return StandardMaterialDefines;
  42905. }(BABYLON.MaterialDefines));
  42906. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42907. var StandardMaterial = /** @class */ (function (_super) {
  42908. __extends(StandardMaterial, _super);
  42909. function StandardMaterial(name, scene) {
  42910. var _this = _super.call(this, name, scene) || this;
  42911. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42912. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42913. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42914. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42915. _this.specularPower = 64;
  42916. _this._useAlphaFromDiffuseTexture = false;
  42917. _this._useEmissiveAsIllumination = false;
  42918. _this._linkEmissiveWithDiffuse = false;
  42919. _this._useSpecularOverAlpha = false;
  42920. _this._useReflectionOverAlpha = false;
  42921. _this._disableLighting = false;
  42922. _this._useObjectSpaceNormalMap = false;
  42923. _this._useParallax = false;
  42924. _this._useParallaxOcclusion = false;
  42925. _this.parallaxScaleBias = 0.05;
  42926. _this._roughness = 0;
  42927. _this.indexOfRefraction = 0.98;
  42928. _this.invertRefractionY = true;
  42929. /**
  42930. * Defines the alpha limits in alpha test mode
  42931. */
  42932. _this.alphaCutOff = 0.4;
  42933. _this._useLightmapAsShadowmap = false;
  42934. _this._useReflectionFresnelFromSpecular = false;
  42935. _this._useGlossinessFromSpecularMapAlpha = false;
  42936. _this._maxSimultaneousLights = 4;
  42937. /**
  42938. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42939. */
  42940. _this._invertNormalMapX = false;
  42941. /**
  42942. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42943. */
  42944. _this._invertNormalMapY = false;
  42945. /**
  42946. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42947. */
  42948. _this._twoSidedLighting = false;
  42949. _this._renderTargets = new BABYLON.SmartArray(16);
  42950. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42951. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42952. // Setup the default processing configuration to the scene.
  42953. _this._attachImageProcessingConfiguration(null);
  42954. _this.getRenderTargetTextures = function () {
  42955. _this._renderTargets.reset();
  42956. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42957. _this._renderTargets.push(_this._reflectionTexture);
  42958. }
  42959. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42960. _this._renderTargets.push(_this._refractionTexture);
  42961. }
  42962. return _this._renderTargets;
  42963. };
  42964. return _this;
  42965. }
  42966. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42967. /**
  42968. * Gets the image processing configuration used either in this material.
  42969. */
  42970. get: function () {
  42971. return this._imageProcessingConfiguration;
  42972. },
  42973. /**
  42974. * Sets the Default image processing configuration used either in the this material.
  42975. *
  42976. * If sets to null, the scene one is in use.
  42977. */
  42978. set: function (value) {
  42979. this._attachImageProcessingConfiguration(value);
  42980. // Ensure the effect will be rebuilt.
  42981. this._markAllSubMeshesAsTexturesDirty();
  42982. },
  42983. enumerable: true,
  42984. configurable: true
  42985. });
  42986. /**
  42987. * Attaches a new image processing configuration to the Standard Material.
  42988. * @param configuration
  42989. */
  42990. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42991. var _this = this;
  42992. if (configuration === this._imageProcessingConfiguration) {
  42993. return;
  42994. }
  42995. // Detaches observer.
  42996. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42997. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42998. }
  42999. // Pick the scene configuration if needed.
  43000. if (!configuration) {
  43001. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43002. }
  43003. else {
  43004. this._imageProcessingConfiguration = configuration;
  43005. }
  43006. // Attaches observer.
  43007. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43008. _this._markAllSubMeshesAsImageProcessingDirty();
  43009. });
  43010. };
  43011. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43012. /**
  43013. * Gets wether the color curves effect is enabled.
  43014. */
  43015. get: function () {
  43016. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43017. },
  43018. /**
  43019. * Sets wether the color curves effect is enabled.
  43020. */
  43021. set: function (value) {
  43022. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43023. },
  43024. enumerable: true,
  43025. configurable: true
  43026. });
  43027. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43028. /**
  43029. * Gets wether the color grading effect is enabled.
  43030. */
  43031. get: function () {
  43032. return this.imageProcessingConfiguration.colorGradingEnabled;
  43033. },
  43034. /**
  43035. * Gets wether the color grading effect is enabled.
  43036. */
  43037. set: function (value) {
  43038. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43039. },
  43040. enumerable: true,
  43041. configurable: true
  43042. });
  43043. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43044. /**
  43045. * Gets wether tonemapping is enabled or not.
  43046. */
  43047. get: function () {
  43048. return this._imageProcessingConfiguration.toneMappingEnabled;
  43049. },
  43050. /**
  43051. * Sets wether tonemapping is enabled or not
  43052. */
  43053. set: function (value) {
  43054. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43055. },
  43056. enumerable: true,
  43057. configurable: true
  43058. });
  43059. ;
  43060. ;
  43061. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43062. /**
  43063. * The camera exposure used on this material.
  43064. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43065. * This corresponds to a photographic exposure.
  43066. */
  43067. get: function () {
  43068. return this._imageProcessingConfiguration.exposure;
  43069. },
  43070. /**
  43071. * The camera exposure used on this material.
  43072. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43073. * This corresponds to a photographic exposure.
  43074. */
  43075. set: function (value) {
  43076. this._imageProcessingConfiguration.exposure = value;
  43077. },
  43078. enumerable: true,
  43079. configurable: true
  43080. });
  43081. ;
  43082. ;
  43083. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43084. /**
  43085. * Gets The camera contrast used on this material.
  43086. */
  43087. get: function () {
  43088. return this._imageProcessingConfiguration.contrast;
  43089. },
  43090. /**
  43091. * Sets The camera contrast used on this material.
  43092. */
  43093. set: function (value) {
  43094. this._imageProcessingConfiguration.contrast = value;
  43095. },
  43096. enumerable: true,
  43097. configurable: true
  43098. });
  43099. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43100. /**
  43101. * Gets the Color Grading 2D Lookup Texture.
  43102. */
  43103. get: function () {
  43104. return this._imageProcessingConfiguration.colorGradingTexture;
  43105. },
  43106. /**
  43107. * Sets the Color Grading 2D Lookup Texture.
  43108. */
  43109. set: function (value) {
  43110. this._imageProcessingConfiguration.colorGradingTexture = value;
  43111. },
  43112. enumerable: true,
  43113. configurable: true
  43114. });
  43115. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43116. /**
  43117. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43118. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43119. * 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;
  43120. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43121. */
  43122. get: function () {
  43123. return this._imageProcessingConfiguration.colorCurves;
  43124. },
  43125. /**
  43126. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43127. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43128. * 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;
  43129. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43130. */
  43131. set: function (value) {
  43132. this._imageProcessingConfiguration.colorCurves = value;
  43133. },
  43134. enumerable: true,
  43135. configurable: true
  43136. });
  43137. StandardMaterial.prototype.getClassName = function () {
  43138. return "StandardMaterial";
  43139. };
  43140. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43141. get: function () {
  43142. return this._useLogarithmicDepth;
  43143. },
  43144. set: function (value) {
  43145. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43146. this._markAllSubMeshesAsMiscDirty();
  43147. },
  43148. enumerable: true,
  43149. configurable: true
  43150. });
  43151. StandardMaterial.prototype.needAlphaBlending = function () {
  43152. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43153. };
  43154. StandardMaterial.prototype.needAlphaTesting = function () {
  43155. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43156. };
  43157. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43158. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43159. };
  43160. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43161. return this._diffuseTexture;
  43162. };
  43163. /**
  43164. * Child classes can use it to update shaders
  43165. */
  43166. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43167. if (useInstances === void 0) { useInstances = false; }
  43168. if (subMesh.effect && this.isFrozen) {
  43169. if (this._wasPreviouslyReady && subMesh.effect) {
  43170. return true;
  43171. }
  43172. }
  43173. if (!subMesh._materialDefines) {
  43174. subMesh._materialDefines = new StandardMaterialDefines();
  43175. }
  43176. var scene = this.getScene();
  43177. var defines = subMesh._materialDefines;
  43178. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43179. if (defines._renderId === scene.getRenderId()) {
  43180. return true;
  43181. }
  43182. }
  43183. var engine = scene.getEngine();
  43184. // Lights
  43185. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43186. // Textures
  43187. if (defines._areTexturesDirty) {
  43188. defines._needUVs = false;
  43189. defines.MAINUV1 = false;
  43190. defines.MAINUV2 = false;
  43191. if (scene.texturesEnabled) {
  43192. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43193. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43194. return false;
  43195. }
  43196. else {
  43197. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43198. }
  43199. }
  43200. else {
  43201. defines.DIFFUSE = false;
  43202. }
  43203. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43204. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43205. return false;
  43206. }
  43207. else {
  43208. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43209. }
  43210. }
  43211. else {
  43212. defines.AMBIENT = false;
  43213. }
  43214. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43215. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43216. return false;
  43217. }
  43218. else {
  43219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43220. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43221. }
  43222. }
  43223. else {
  43224. defines.OPACITY = false;
  43225. }
  43226. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43227. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43228. return false;
  43229. }
  43230. else {
  43231. defines._needNormals = true;
  43232. defines.REFLECTION = true;
  43233. defines.ROUGHNESS = (this._roughness > 0);
  43234. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43235. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43236. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43237. switch (this._reflectionTexture.coordinatesMode) {
  43238. case BABYLON.Texture.EXPLICIT_MODE:
  43239. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43240. break;
  43241. case BABYLON.Texture.PLANAR_MODE:
  43242. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43243. break;
  43244. case BABYLON.Texture.PROJECTION_MODE:
  43245. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43246. break;
  43247. case BABYLON.Texture.SKYBOX_MODE:
  43248. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43249. break;
  43250. case BABYLON.Texture.SPHERICAL_MODE:
  43251. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43252. break;
  43253. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43254. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43255. break;
  43256. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43257. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43258. break;
  43259. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43260. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43261. break;
  43262. case BABYLON.Texture.CUBIC_MODE:
  43263. case BABYLON.Texture.INVCUBIC_MODE:
  43264. default:
  43265. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43266. break;
  43267. }
  43268. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43269. }
  43270. }
  43271. else {
  43272. defines.REFLECTION = false;
  43273. }
  43274. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43275. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43276. return false;
  43277. }
  43278. else {
  43279. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43280. }
  43281. }
  43282. else {
  43283. defines.EMISSIVE = false;
  43284. }
  43285. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43286. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43287. return false;
  43288. }
  43289. else {
  43290. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43291. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43292. }
  43293. }
  43294. else {
  43295. defines.LIGHTMAP = false;
  43296. }
  43297. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43298. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43299. return false;
  43300. }
  43301. else {
  43302. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43303. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43304. }
  43305. }
  43306. else {
  43307. defines.SPECULAR = false;
  43308. }
  43309. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43310. // Bump texure can not be not blocking.
  43311. if (!this._bumpTexture.isReady()) {
  43312. return false;
  43313. }
  43314. else {
  43315. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43316. defines.PARALLAX = this._useParallax;
  43317. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43318. }
  43319. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43320. }
  43321. else {
  43322. defines.BUMP = false;
  43323. }
  43324. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43325. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43326. return false;
  43327. }
  43328. else {
  43329. defines._needUVs = true;
  43330. defines.REFRACTION = true;
  43331. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43332. }
  43333. }
  43334. else {
  43335. defines.REFRACTION = false;
  43336. }
  43337. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43338. }
  43339. else {
  43340. defines.DIFFUSE = false;
  43341. defines.AMBIENT = false;
  43342. defines.OPACITY = false;
  43343. defines.REFLECTION = false;
  43344. defines.EMISSIVE = false;
  43345. defines.LIGHTMAP = false;
  43346. defines.BUMP = false;
  43347. defines.REFRACTION = false;
  43348. }
  43349. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43350. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43351. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43352. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43353. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43354. }
  43355. if (defines._areImageProcessingDirty) {
  43356. if (!this._imageProcessingConfiguration.isReady()) {
  43357. return false;
  43358. }
  43359. this._imageProcessingConfiguration.prepareDefines(defines);
  43360. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43361. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43362. }
  43363. if (defines._areFresnelDirty) {
  43364. if (StandardMaterial.FresnelEnabled) {
  43365. // Fresnel
  43366. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43367. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43368. this._reflectionFresnelParameters) {
  43369. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43370. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43371. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43372. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43373. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43374. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43375. defines._needNormals = true;
  43376. defines.FRESNEL = true;
  43377. }
  43378. }
  43379. else {
  43380. defines.FRESNEL = false;
  43381. }
  43382. }
  43383. // Misc.
  43384. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43385. // Attribs
  43386. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43387. // Values that need to be evaluated on every frame
  43388. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43389. // Get correct effect
  43390. if (defines.isDirty) {
  43391. defines.markAsProcessed();
  43392. scene.resetCachedMaterial();
  43393. // Fallbacks
  43394. var fallbacks = new BABYLON.EffectFallbacks();
  43395. if (defines.REFLECTION) {
  43396. fallbacks.addFallback(0, "REFLECTION");
  43397. }
  43398. if (defines.SPECULAR) {
  43399. fallbacks.addFallback(0, "SPECULAR");
  43400. }
  43401. if (defines.BUMP) {
  43402. fallbacks.addFallback(0, "BUMP");
  43403. }
  43404. if (defines.PARALLAX) {
  43405. fallbacks.addFallback(1, "PARALLAX");
  43406. }
  43407. if (defines.PARALLAXOCCLUSION) {
  43408. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43409. }
  43410. if (defines.SPECULAROVERALPHA) {
  43411. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43412. }
  43413. if (defines.FOG) {
  43414. fallbacks.addFallback(1, "FOG");
  43415. }
  43416. if (defines.POINTSIZE) {
  43417. fallbacks.addFallback(0, "POINTSIZE");
  43418. }
  43419. if (defines.LOGARITHMICDEPTH) {
  43420. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43421. }
  43422. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43423. if (defines.SPECULARTERM) {
  43424. fallbacks.addFallback(0, "SPECULARTERM");
  43425. }
  43426. if (defines.DIFFUSEFRESNEL) {
  43427. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43428. }
  43429. if (defines.OPACITYFRESNEL) {
  43430. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43431. }
  43432. if (defines.REFLECTIONFRESNEL) {
  43433. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43434. }
  43435. if (defines.EMISSIVEFRESNEL) {
  43436. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43437. }
  43438. if (defines.FRESNEL) {
  43439. fallbacks.addFallback(4, "FRESNEL");
  43440. }
  43441. //Attributes
  43442. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43443. if (defines.NORMAL) {
  43444. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43445. }
  43446. if (defines.UV1) {
  43447. attribs.push(BABYLON.VertexBuffer.UVKind);
  43448. }
  43449. if (defines.UV2) {
  43450. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43451. }
  43452. if (defines.VERTEXCOLOR) {
  43453. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43454. }
  43455. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43456. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43457. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43458. var shaderName = "default";
  43459. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43460. "vFogInfos", "vFogColor", "pointSize",
  43461. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43462. "mBones",
  43463. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43464. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43465. "vReflectionPosition", "vReflectionSize",
  43466. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43467. ];
  43468. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43469. var uniformBuffers = ["Material", "Scene"];
  43470. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43471. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43472. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43473. uniformsNames: uniforms,
  43474. uniformBuffersNames: uniformBuffers,
  43475. samplers: samplers,
  43476. defines: defines,
  43477. maxSimultaneousLights: this._maxSimultaneousLights
  43478. });
  43479. if (this.customShaderNameResolve) {
  43480. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43481. }
  43482. var join = defines.toString();
  43483. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43484. attributes: attribs,
  43485. uniformsNames: uniforms,
  43486. uniformBuffersNames: uniformBuffers,
  43487. samplers: samplers,
  43488. defines: join,
  43489. fallbacks: fallbacks,
  43490. onCompiled: this.onCompiled,
  43491. onError: this.onError,
  43492. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43493. }, engine), defines);
  43494. this.buildUniformLayout();
  43495. }
  43496. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43497. return false;
  43498. }
  43499. defines._renderId = scene.getRenderId();
  43500. this._wasPreviouslyReady = true;
  43501. return true;
  43502. };
  43503. StandardMaterial.prototype.buildUniformLayout = function () {
  43504. // Order is important !
  43505. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43506. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43507. this._uniformBuffer.addUniform("opacityParts", 4);
  43508. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43509. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43510. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43511. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43512. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43513. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43514. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43515. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43516. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43517. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43518. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43519. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43520. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43521. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43522. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43523. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43524. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43525. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43526. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43527. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43528. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43529. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43530. this._uniformBuffer.addUniform("specularMatrix", 16);
  43531. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43532. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43533. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43534. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43535. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43536. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43537. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43538. this._uniformBuffer.addUniform("pointSize", 1);
  43539. this._uniformBuffer.create();
  43540. };
  43541. StandardMaterial.prototype.unbind = function () {
  43542. if (this._activeEffect) {
  43543. var needFlag = false;
  43544. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43545. this._activeEffect.setTexture("reflection2DSampler", null);
  43546. needFlag = true;
  43547. }
  43548. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43549. this._activeEffect.setTexture("refraction2DSampler", null);
  43550. needFlag = true;
  43551. }
  43552. if (needFlag) {
  43553. this._markAllSubMeshesAsTexturesDirty();
  43554. }
  43555. }
  43556. _super.prototype.unbind.call(this);
  43557. };
  43558. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43559. var scene = this.getScene();
  43560. var defines = subMesh._materialDefines;
  43561. if (!defines) {
  43562. return;
  43563. }
  43564. var effect = subMesh.effect;
  43565. if (!effect) {
  43566. return;
  43567. }
  43568. this._activeEffect = effect;
  43569. // Matrices
  43570. this.bindOnlyWorldMatrix(world);
  43571. // Normal Matrix
  43572. if (defines.OBJECTSPACE_NORMALMAP) {
  43573. world.toNormalMatrix(this._normalMatrix);
  43574. this.bindOnlyNormalMatrix(this._normalMatrix);
  43575. }
  43576. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43577. // Bones
  43578. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43579. if (mustRebind) {
  43580. this._uniformBuffer.bindToEffect(effect, "Material");
  43581. this.bindViewProjection(effect);
  43582. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43583. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43584. // Fresnel
  43585. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43586. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43587. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43588. }
  43589. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43590. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43591. }
  43592. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43593. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43594. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43595. }
  43596. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43597. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43598. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43599. }
  43600. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43601. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43602. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43603. }
  43604. }
  43605. // Textures
  43606. if (scene.texturesEnabled) {
  43607. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43608. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43609. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43610. if (this._diffuseTexture.hasAlpha) {
  43611. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43612. }
  43613. }
  43614. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43615. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43616. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43617. }
  43618. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43619. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43620. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43621. }
  43622. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43623. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43624. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43625. if (this._reflectionTexture.boundingBoxSize) {
  43626. var cubeTexture = this._reflectionTexture;
  43627. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43628. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43629. }
  43630. }
  43631. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43632. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43633. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43634. }
  43635. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43636. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43637. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43638. }
  43639. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43640. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43641. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43642. }
  43643. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43644. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43645. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43646. if (scene._mirroredCameraPosition) {
  43647. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43648. }
  43649. else {
  43650. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43651. }
  43652. }
  43653. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43654. var depth = 1.0;
  43655. if (!this._refractionTexture.isCube) {
  43656. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43657. if (this._refractionTexture.depth) {
  43658. depth = this._refractionTexture.depth;
  43659. }
  43660. }
  43661. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43662. }
  43663. }
  43664. // Point size
  43665. if (this.pointsCloud) {
  43666. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43667. }
  43668. if (defines.SPECULARTERM) {
  43669. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43670. }
  43671. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43672. // Diffuse
  43673. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43674. }
  43675. // Textures
  43676. if (scene.texturesEnabled) {
  43677. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43678. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43679. }
  43680. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43681. effect.setTexture("ambientSampler", this._ambientTexture);
  43682. }
  43683. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43684. effect.setTexture("opacitySampler", this._opacityTexture);
  43685. }
  43686. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43687. if (this._reflectionTexture.isCube) {
  43688. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43689. }
  43690. else {
  43691. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43692. }
  43693. }
  43694. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43695. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43696. }
  43697. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43698. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43699. }
  43700. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43701. effect.setTexture("specularSampler", this._specularTexture);
  43702. }
  43703. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43704. effect.setTexture("bumpSampler", this._bumpTexture);
  43705. }
  43706. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43707. var depth = 1.0;
  43708. if (this._refractionTexture.isCube) {
  43709. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43710. }
  43711. else {
  43712. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43713. }
  43714. }
  43715. }
  43716. // Clip plane
  43717. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43718. // Colors
  43719. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43720. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43721. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43722. }
  43723. if (mustRebind || !this.isFrozen) {
  43724. // Lights
  43725. if (scene.lightsEnabled && !this._disableLighting) {
  43726. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43727. }
  43728. // View
  43729. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43730. this.bindView(effect);
  43731. }
  43732. // Fog
  43733. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43734. // Morph targets
  43735. if (defines.NUM_MORPH_INFLUENCERS) {
  43736. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43737. }
  43738. // Log. depth
  43739. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43740. // image processing
  43741. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43742. this._imageProcessingConfiguration.bind(this._activeEffect);
  43743. }
  43744. }
  43745. this._uniformBuffer.update();
  43746. this._afterBind(mesh, this._activeEffect);
  43747. };
  43748. StandardMaterial.prototype.getAnimatables = function () {
  43749. var results = [];
  43750. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43751. results.push(this._diffuseTexture);
  43752. }
  43753. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43754. results.push(this._ambientTexture);
  43755. }
  43756. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43757. results.push(this._opacityTexture);
  43758. }
  43759. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43760. results.push(this._reflectionTexture);
  43761. }
  43762. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43763. results.push(this._emissiveTexture);
  43764. }
  43765. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43766. results.push(this._specularTexture);
  43767. }
  43768. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43769. results.push(this._bumpTexture);
  43770. }
  43771. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43772. results.push(this._lightmapTexture);
  43773. }
  43774. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43775. results.push(this._refractionTexture);
  43776. }
  43777. return results;
  43778. };
  43779. StandardMaterial.prototype.getActiveTextures = function () {
  43780. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43781. if (this._diffuseTexture) {
  43782. activeTextures.push(this._diffuseTexture);
  43783. }
  43784. if (this._ambientTexture) {
  43785. activeTextures.push(this._ambientTexture);
  43786. }
  43787. if (this._opacityTexture) {
  43788. activeTextures.push(this._opacityTexture);
  43789. }
  43790. if (this._reflectionTexture) {
  43791. activeTextures.push(this._reflectionTexture);
  43792. }
  43793. if (this._emissiveTexture) {
  43794. activeTextures.push(this._emissiveTexture);
  43795. }
  43796. if (this._specularTexture) {
  43797. activeTextures.push(this._specularTexture);
  43798. }
  43799. if (this._bumpTexture) {
  43800. activeTextures.push(this._bumpTexture);
  43801. }
  43802. if (this._lightmapTexture) {
  43803. activeTextures.push(this._lightmapTexture);
  43804. }
  43805. if (this._refractionTexture) {
  43806. activeTextures.push(this._refractionTexture);
  43807. }
  43808. return activeTextures;
  43809. };
  43810. StandardMaterial.prototype.hasTexture = function (texture) {
  43811. if (_super.prototype.hasTexture.call(this, texture)) {
  43812. return true;
  43813. }
  43814. if (this._diffuseTexture === texture) {
  43815. return true;
  43816. }
  43817. if (this._ambientTexture === texture) {
  43818. return true;
  43819. }
  43820. if (this._opacityTexture === texture) {
  43821. return true;
  43822. }
  43823. if (this._reflectionTexture === texture) {
  43824. return true;
  43825. }
  43826. if (this._emissiveTexture === texture) {
  43827. return true;
  43828. }
  43829. if (this._specularTexture === texture) {
  43830. return true;
  43831. }
  43832. if (this._bumpTexture === texture) {
  43833. return true;
  43834. }
  43835. if (this._lightmapTexture === texture) {
  43836. return true;
  43837. }
  43838. if (this._refractionTexture === texture) {
  43839. return true;
  43840. }
  43841. return false;
  43842. };
  43843. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43844. if (forceDisposeTextures) {
  43845. if (this._diffuseTexture) {
  43846. this._diffuseTexture.dispose();
  43847. }
  43848. if (this._ambientTexture) {
  43849. this._ambientTexture.dispose();
  43850. }
  43851. if (this._opacityTexture) {
  43852. this._opacityTexture.dispose();
  43853. }
  43854. if (this._reflectionTexture) {
  43855. this._reflectionTexture.dispose();
  43856. }
  43857. if (this._emissiveTexture) {
  43858. this._emissiveTexture.dispose();
  43859. }
  43860. if (this._specularTexture) {
  43861. this._specularTexture.dispose();
  43862. }
  43863. if (this._bumpTexture) {
  43864. this._bumpTexture.dispose();
  43865. }
  43866. if (this._lightmapTexture) {
  43867. this._lightmapTexture.dispose();
  43868. }
  43869. if (this._refractionTexture) {
  43870. this._refractionTexture.dispose();
  43871. }
  43872. }
  43873. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43874. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43875. }
  43876. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43877. };
  43878. StandardMaterial.prototype.clone = function (name) {
  43879. var _this = this;
  43880. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43881. result.name = name;
  43882. result.id = name;
  43883. return result;
  43884. };
  43885. StandardMaterial.prototype.serialize = function () {
  43886. return BABYLON.SerializationHelper.Serialize(this);
  43887. };
  43888. // Statics
  43889. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43890. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43891. };
  43892. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43893. get: function () {
  43894. return StandardMaterial._DiffuseTextureEnabled;
  43895. },
  43896. set: function (value) {
  43897. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43898. return;
  43899. }
  43900. StandardMaterial._DiffuseTextureEnabled = value;
  43901. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43902. },
  43903. enumerable: true,
  43904. configurable: true
  43905. });
  43906. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43907. get: function () {
  43908. return StandardMaterial._AmbientTextureEnabled;
  43909. },
  43910. set: function (value) {
  43911. if (StandardMaterial._AmbientTextureEnabled === value) {
  43912. return;
  43913. }
  43914. StandardMaterial._AmbientTextureEnabled = value;
  43915. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43916. },
  43917. enumerable: true,
  43918. configurable: true
  43919. });
  43920. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43921. get: function () {
  43922. return StandardMaterial._OpacityTextureEnabled;
  43923. },
  43924. set: function (value) {
  43925. if (StandardMaterial._OpacityTextureEnabled === value) {
  43926. return;
  43927. }
  43928. StandardMaterial._OpacityTextureEnabled = value;
  43929. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43930. },
  43931. enumerable: true,
  43932. configurable: true
  43933. });
  43934. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43935. get: function () {
  43936. return StandardMaterial._ReflectionTextureEnabled;
  43937. },
  43938. set: function (value) {
  43939. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43940. return;
  43941. }
  43942. StandardMaterial._ReflectionTextureEnabled = value;
  43943. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43944. },
  43945. enumerable: true,
  43946. configurable: true
  43947. });
  43948. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43949. get: function () {
  43950. return StandardMaterial._EmissiveTextureEnabled;
  43951. },
  43952. set: function (value) {
  43953. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43954. return;
  43955. }
  43956. StandardMaterial._EmissiveTextureEnabled = value;
  43957. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43958. },
  43959. enumerable: true,
  43960. configurable: true
  43961. });
  43962. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43963. get: function () {
  43964. return StandardMaterial._SpecularTextureEnabled;
  43965. },
  43966. set: function (value) {
  43967. if (StandardMaterial._SpecularTextureEnabled === value) {
  43968. return;
  43969. }
  43970. StandardMaterial._SpecularTextureEnabled = value;
  43971. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43972. },
  43973. enumerable: true,
  43974. configurable: true
  43975. });
  43976. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43977. get: function () {
  43978. return StandardMaterial._BumpTextureEnabled;
  43979. },
  43980. set: function (value) {
  43981. if (StandardMaterial._BumpTextureEnabled === value) {
  43982. return;
  43983. }
  43984. StandardMaterial._BumpTextureEnabled = value;
  43985. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43986. },
  43987. enumerable: true,
  43988. configurable: true
  43989. });
  43990. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43991. get: function () {
  43992. return StandardMaterial._LightmapTextureEnabled;
  43993. },
  43994. set: function (value) {
  43995. if (StandardMaterial._LightmapTextureEnabled === value) {
  43996. return;
  43997. }
  43998. StandardMaterial._LightmapTextureEnabled = value;
  43999. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44000. },
  44001. enumerable: true,
  44002. configurable: true
  44003. });
  44004. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44005. get: function () {
  44006. return StandardMaterial._RefractionTextureEnabled;
  44007. },
  44008. set: function (value) {
  44009. if (StandardMaterial._RefractionTextureEnabled === value) {
  44010. return;
  44011. }
  44012. StandardMaterial._RefractionTextureEnabled = value;
  44013. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44014. },
  44015. enumerable: true,
  44016. configurable: true
  44017. });
  44018. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44019. get: function () {
  44020. return StandardMaterial._ColorGradingTextureEnabled;
  44021. },
  44022. set: function (value) {
  44023. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44024. return;
  44025. }
  44026. StandardMaterial._ColorGradingTextureEnabled = value;
  44027. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44028. },
  44029. enumerable: true,
  44030. configurable: true
  44031. });
  44032. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44033. get: function () {
  44034. return StandardMaterial._FresnelEnabled;
  44035. },
  44036. set: function (value) {
  44037. if (StandardMaterial._FresnelEnabled === value) {
  44038. return;
  44039. }
  44040. StandardMaterial._FresnelEnabled = value;
  44041. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44042. },
  44043. enumerable: true,
  44044. configurable: true
  44045. });
  44046. // Flags used to enable or disable a type of texture for all Standard Materials
  44047. StandardMaterial._DiffuseTextureEnabled = true;
  44048. StandardMaterial._AmbientTextureEnabled = true;
  44049. StandardMaterial._OpacityTextureEnabled = true;
  44050. StandardMaterial._ReflectionTextureEnabled = true;
  44051. StandardMaterial._EmissiveTextureEnabled = true;
  44052. StandardMaterial._SpecularTextureEnabled = true;
  44053. StandardMaterial._BumpTextureEnabled = true;
  44054. StandardMaterial._LightmapTextureEnabled = true;
  44055. StandardMaterial._RefractionTextureEnabled = true;
  44056. StandardMaterial._ColorGradingTextureEnabled = true;
  44057. StandardMaterial._FresnelEnabled = true;
  44058. __decorate([
  44059. BABYLON.serializeAsTexture("diffuseTexture")
  44060. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44061. __decorate([
  44062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44063. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44064. __decorate([
  44065. BABYLON.serializeAsTexture("ambientTexture")
  44066. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44067. __decorate([
  44068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44069. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44070. __decorate([
  44071. BABYLON.serializeAsTexture("opacityTexture")
  44072. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44073. __decorate([
  44074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44075. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44076. __decorate([
  44077. BABYLON.serializeAsTexture("reflectionTexture")
  44078. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44079. __decorate([
  44080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44081. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44082. __decorate([
  44083. BABYLON.serializeAsTexture("emissiveTexture")
  44084. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44085. __decorate([
  44086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44087. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44088. __decorate([
  44089. BABYLON.serializeAsTexture("specularTexture")
  44090. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44091. __decorate([
  44092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44093. ], StandardMaterial.prototype, "specularTexture", void 0);
  44094. __decorate([
  44095. BABYLON.serializeAsTexture("bumpTexture")
  44096. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44097. __decorate([
  44098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44099. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44100. __decorate([
  44101. BABYLON.serializeAsTexture("lightmapTexture")
  44102. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44103. __decorate([
  44104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44105. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44106. __decorate([
  44107. BABYLON.serializeAsTexture("refractionTexture")
  44108. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44109. __decorate([
  44110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44111. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44112. __decorate([
  44113. BABYLON.serializeAsColor3("ambient")
  44114. ], StandardMaterial.prototype, "ambientColor", void 0);
  44115. __decorate([
  44116. BABYLON.serializeAsColor3("diffuse")
  44117. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44118. __decorate([
  44119. BABYLON.serializeAsColor3("specular")
  44120. ], StandardMaterial.prototype, "specularColor", void 0);
  44121. __decorate([
  44122. BABYLON.serializeAsColor3("emissive")
  44123. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44124. __decorate([
  44125. BABYLON.serialize()
  44126. ], StandardMaterial.prototype, "specularPower", void 0);
  44127. __decorate([
  44128. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44129. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44130. __decorate([
  44131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44132. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44133. __decorate([
  44134. BABYLON.serialize("useEmissiveAsIllumination")
  44135. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44136. __decorate([
  44137. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44138. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44139. __decorate([
  44140. BABYLON.serialize("linkEmissiveWithDiffuse")
  44141. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44142. __decorate([
  44143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44144. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44145. __decorate([
  44146. BABYLON.serialize("useSpecularOverAlpha")
  44147. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44148. __decorate([
  44149. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44150. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44151. __decorate([
  44152. BABYLON.serialize("useReflectionOverAlpha")
  44153. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44154. __decorate([
  44155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44156. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44157. __decorate([
  44158. BABYLON.serialize("disableLighting")
  44159. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44160. __decorate([
  44161. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44162. ], StandardMaterial.prototype, "disableLighting", void 0);
  44163. __decorate([
  44164. BABYLON.serialize("useObjectSpaceNormalMap")
  44165. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44166. __decorate([
  44167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44168. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44169. __decorate([
  44170. BABYLON.serialize("useParallax")
  44171. ], StandardMaterial.prototype, "_useParallax", void 0);
  44172. __decorate([
  44173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44174. ], StandardMaterial.prototype, "useParallax", void 0);
  44175. __decorate([
  44176. BABYLON.serialize("useParallaxOcclusion")
  44177. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44178. __decorate([
  44179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44180. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44181. __decorate([
  44182. BABYLON.serialize()
  44183. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44184. __decorate([
  44185. BABYLON.serialize("roughness")
  44186. ], StandardMaterial.prototype, "_roughness", void 0);
  44187. __decorate([
  44188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44189. ], StandardMaterial.prototype, "roughness", void 0);
  44190. __decorate([
  44191. BABYLON.serialize()
  44192. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44193. __decorate([
  44194. BABYLON.serialize()
  44195. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44196. __decorate([
  44197. BABYLON.serialize()
  44198. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44199. __decorate([
  44200. BABYLON.serialize("useLightmapAsShadowmap")
  44201. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44202. __decorate([
  44203. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44204. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44205. __decorate([
  44206. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44207. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44208. __decorate([
  44209. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44210. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44211. __decorate([
  44212. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44213. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44214. __decorate([
  44215. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44216. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44217. __decorate([
  44218. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44219. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44220. __decorate([
  44221. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44222. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44223. __decorate([
  44224. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44225. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44226. __decorate([
  44227. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44228. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44229. __decorate([
  44230. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44231. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44232. __decorate([
  44233. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44234. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44235. __decorate([
  44236. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44237. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44238. __decorate([
  44239. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44240. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44241. __decorate([
  44242. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44243. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44244. __decorate([
  44245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44246. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44247. __decorate([
  44248. BABYLON.serialize("maxSimultaneousLights")
  44249. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44250. __decorate([
  44251. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44252. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44253. __decorate([
  44254. BABYLON.serialize("invertNormalMapX")
  44255. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44256. __decorate([
  44257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44258. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44259. __decorate([
  44260. BABYLON.serialize("invertNormalMapY")
  44261. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44262. __decorate([
  44263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44264. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44265. __decorate([
  44266. BABYLON.serialize("twoSidedLighting")
  44267. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44268. __decorate([
  44269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44270. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44271. __decorate([
  44272. BABYLON.serialize()
  44273. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44274. return StandardMaterial;
  44275. }(BABYLON.PushMaterial));
  44276. BABYLON.StandardMaterial = StandardMaterial;
  44277. })(BABYLON || (BABYLON = {}));
  44278. //# sourceMappingURL=babylon.standardMaterial.js.map
  44279. var BABYLON;
  44280. (function (BABYLON) {
  44281. /**
  44282. * Manages the defines for the PBR Material.
  44283. * @hiddenChildren
  44284. */
  44285. var PBRMaterialDefines = /** @class */ (function (_super) {
  44286. __extends(PBRMaterialDefines, _super);
  44287. /**
  44288. * Initializes the PBR Material defines.
  44289. */
  44290. function PBRMaterialDefines() {
  44291. var _this = _super.call(this) || this;
  44292. _this.PBR = true;
  44293. _this.MAINUV1 = false;
  44294. _this.MAINUV2 = false;
  44295. _this.UV1 = false;
  44296. _this.UV2 = false;
  44297. _this.ALBEDO = false;
  44298. _this.ALBEDODIRECTUV = 0;
  44299. _this.VERTEXCOLOR = false;
  44300. _this.AMBIENT = false;
  44301. _this.AMBIENTDIRECTUV = 0;
  44302. _this.AMBIENTINGRAYSCALE = false;
  44303. _this.OPACITY = false;
  44304. _this.VERTEXALPHA = false;
  44305. _this.OPACITYDIRECTUV = 0;
  44306. _this.OPACITYRGB = false;
  44307. _this.ALPHATEST = false;
  44308. _this.DEPTHPREPASS = false;
  44309. _this.ALPHABLEND = false;
  44310. _this.ALPHAFROMALBEDO = false;
  44311. _this.ALPHATESTVALUE = "0.5";
  44312. _this.SPECULAROVERALPHA = false;
  44313. _this.RADIANCEOVERALPHA = false;
  44314. _this.ALPHAFRESNEL = false;
  44315. _this.LINEARALPHAFRESNEL = false;
  44316. _this.PREMULTIPLYALPHA = false;
  44317. _this.EMISSIVE = false;
  44318. _this.EMISSIVEDIRECTUV = 0;
  44319. _this.REFLECTIVITY = false;
  44320. _this.REFLECTIVITYDIRECTUV = 0;
  44321. _this.SPECULARTERM = false;
  44322. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44323. _this.MICROSURFACEAUTOMATIC = false;
  44324. _this.LODBASEDMICROSFURACE = false;
  44325. _this.MICROSURFACEMAP = false;
  44326. _this.MICROSURFACEMAPDIRECTUV = 0;
  44327. _this.METALLICWORKFLOW = false;
  44328. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44329. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44330. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44331. _this.AOSTOREINMETALMAPRED = false;
  44332. _this.ENVIRONMENTBRDF = false;
  44333. _this.NORMAL = false;
  44334. _this.TANGENT = false;
  44335. _this.BUMP = false;
  44336. _this.BUMPDIRECTUV = 0;
  44337. _this.OBJECTSPACE_NORMALMAP = false;
  44338. _this.PARALLAX = false;
  44339. _this.PARALLAXOCCLUSION = false;
  44340. _this.NORMALXYSCALE = true;
  44341. _this.LIGHTMAP = false;
  44342. _this.LIGHTMAPDIRECTUV = 0;
  44343. _this.USELIGHTMAPASSHADOWMAP = false;
  44344. _this.GAMMALIGHTMAP = false;
  44345. _this.REFLECTION = false;
  44346. _this.REFLECTIONMAP_3D = false;
  44347. _this.REFLECTIONMAP_SPHERICAL = false;
  44348. _this.REFLECTIONMAP_PLANAR = false;
  44349. _this.REFLECTIONMAP_CUBIC = false;
  44350. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44351. _this.REFLECTIONMAP_PROJECTION = false;
  44352. _this.REFLECTIONMAP_SKYBOX = false;
  44353. _this.REFLECTIONMAP_EXPLICIT = false;
  44354. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44355. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44356. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44357. _this.INVERTCUBICMAP = false;
  44358. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44359. _this.USESPHERICALINVERTEX = false;
  44360. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44361. _this.LODINREFLECTIONALPHA = false;
  44362. _this.GAMMAREFLECTION = false;
  44363. _this.RADIANCEOCCLUSION = false;
  44364. _this.HORIZONOCCLUSION = false;
  44365. _this.REFRACTION = false;
  44366. _this.REFRACTIONMAP_3D = false;
  44367. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44368. _this.LODINREFRACTIONALPHA = false;
  44369. _this.GAMMAREFRACTION = false;
  44370. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44371. _this.INSTANCES = false;
  44372. _this.NUM_BONE_INFLUENCERS = 0;
  44373. _this.BonesPerMesh = 0;
  44374. _this.NONUNIFORMSCALING = false;
  44375. _this.MORPHTARGETS = false;
  44376. _this.MORPHTARGETS_NORMAL = false;
  44377. _this.MORPHTARGETS_TANGENT = false;
  44378. _this.NUM_MORPH_INFLUENCERS = 0;
  44379. _this.IMAGEPROCESSING = false;
  44380. _this.VIGNETTE = false;
  44381. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44382. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44383. _this.TONEMAPPING = false;
  44384. _this.CONTRAST = false;
  44385. _this.COLORCURVES = false;
  44386. _this.COLORGRADING = false;
  44387. _this.COLORGRADING3D = false;
  44388. _this.SAMPLER3DGREENDEPTH = false;
  44389. _this.SAMPLER3DBGRMAP = false;
  44390. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44391. _this.EXPOSURE = false;
  44392. _this.USEPHYSICALLIGHTFALLOFF = false;
  44393. _this.TWOSIDEDLIGHTING = false;
  44394. _this.SHADOWFLOAT = false;
  44395. _this.CLIPPLANE = false;
  44396. _this.POINTSIZE = false;
  44397. _this.FOG = false;
  44398. _this.LOGARITHMICDEPTH = false;
  44399. _this.FORCENORMALFORWARD = false;
  44400. _this.SPECULARAA = false;
  44401. _this.UNLIT = false;
  44402. _this.rebuild();
  44403. return _this;
  44404. }
  44405. /**
  44406. * Resets the PBR Material defines.
  44407. */
  44408. PBRMaterialDefines.prototype.reset = function () {
  44409. _super.prototype.reset.call(this);
  44410. this.ALPHATESTVALUE = "0.5";
  44411. this.PBR = true;
  44412. };
  44413. return PBRMaterialDefines;
  44414. }(BABYLON.MaterialDefines));
  44415. /**
  44416. * The Physically based material base class of BJS.
  44417. *
  44418. * This offers the main features of a standard PBR material.
  44419. * For more information, please refer to the documentation :
  44420. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44421. */
  44422. var PBRBaseMaterial = /** @class */ (function (_super) {
  44423. __extends(PBRBaseMaterial, _super);
  44424. /**
  44425. * Instantiates a new PBRMaterial instance.
  44426. *
  44427. * @param name The material name
  44428. * @param scene The scene the material will be use in.
  44429. */
  44430. function PBRBaseMaterial(name, scene) {
  44431. var _this = _super.call(this, name, scene) || this;
  44432. /**
  44433. * Intensity of the direct lights e.g. the four lights available in your scene.
  44434. * This impacts both the direct diffuse and specular highlights.
  44435. */
  44436. _this._directIntensity = 1.0;
  44437. /**
  44438. * Intensity of the emissive part of the material.
  44439. * This helps controlling the emissive effect without modifying the emissive color.
  44440. */
  44441. _this._emissiveIntensity = 1.0;
  44442. /**
  44443. * Intensity of the environment e.g. how much the environment will light the object
  44444. * either through harmonics for rough material or through the refelction for shiny ones.
  44445. */
  44446. _this._environmentIntensity = 1.0;
  44447. /**
  44448. * This is a special control allowing the reduction of the specular highlights coming from the
  44449. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44450. */
  44451. _this._specularIntensity = 1.0;
  44452. /**
  44453. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44454. */
  44455. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44456. /**
  44457. * Debug Control allowing disabling the bump map on this material.
  44458. */
  44459. _this._disableBumpMap = false;
  44460. /**
  44461. * AKA Occlusion Texture Intensity in other nomenclature.
  44462. */
  44463. _this._ambientTextureStrength = 1.0;
  44464. /**
  44465. * The color of a material in ambient lighting.
  44466. */
  44467. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44468. /**
  44469. * AKA Diffuse Color in other nomenclature.
  44470. */
  44471. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44472. /**
  44473. * AKA Specular Color in other nomenclature.
  44474. */
  44475. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44476. /**
  44477. * The color applied when light is reflected from a material.
  44478. */
  44479. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44480. /**
  44481. * The color applied when light is emitted from a material.
  44482. */
  44483. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44484. /**
  44485. * AKA Glossiness in other nomenclature.
  44486. */
  44487. _this._microSurface = 0.9;
  44488. /**
  44489. * source material index of refraction (IOR)' / 'destination material IOR.
  44490. */
  44491. _this._indexOfRefraction = 0.66;
  44492. /**
  44493. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44494. */
  44495. _this._invertRefractionY = false;
  44496. /**
  44497. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44498. * Materials half opaque for instance using refraction could benefit from this control.
  44499. */
  44500. _this._linkRefractionWithTransparency = false;
  44501. /**
  44502. * Specifies that the material will use the light map as a show map.
  44503. */
  44504. _this._useLightmapAsShadowmap = false;
  44505. /**
  44506. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44507. * makes the reflect vector face the model (under horizon).
  44508. */
  44509. _this._useHorizonOcclusion = true;
  44510. /**
  44511. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44512. * too much the area relying on ambient texture to define their ambient occlusion.
  44513. */
  44514. _this._useRadianceOcclusion = true;
  44515. /**
  44516. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44517. */
  44518. _this._useAlphaFromAlbedoTexture = false;
  44519. /**
  44520. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44521. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44522. */
  44523. _this._useSpecularOverAlpha = true;
  44524. /**
  44525. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44526. */
  44527. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44528. /**
  44529. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44530. */
  44531. _this._useRoughnessFromMetallicTextureAlpha = true;
  44532. /**
  44533. * Specifies if the metallic texture contains the roughness information in its green channel.
  44534. */
  44535. _this._useRoughnessFromMetallicTextureGreen = false;
  44536. /**
  44537. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44538. */
  44539. _this._useMetallnessFromMetallicTextureBlue = false;
  44540. /**
  44541. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44542. */
  44543. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44544. /**
  44545. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44546. */
  44547. _this._useAmbientInGrayScale = false;
  44548. /**
  44549. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44550. * The material will try to infer what glossiness each pixel should be.
  44551. */
  44552. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44553. /**
  44554. * BJS is using an harcoded light falloff based on a manually sets up range.
  44555. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44556. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44557. */
  44558. _this._usePhysicalLightFalloff = true;
  44559. /**
  44560. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44561. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44562. */
  44563. _this._useRadianceOverAlpha = true;
  44564. /**
  44565. * Allows using an object space normal map (instead of tangent space).
  44566. */
  44567. _this._useObjectSpaceNormalMap = false;
  44568. /**
  44569. * Allows using the bump map in parallax mode.
  44570. */
  44571. _this._useParallax = false;
  44572. /**
  44573. * Allows using the bump map in parallax occlusion mode.
  44574. */
  44575. _this._useParallaxOcclusion = false;
  44576. /**
  44577. * Controls the scale bias of the parallax mode.
  44578. */
  44579. _this._parallaxScaleBias = 0.05;
  44580. /**
  44581. * If sets to true, disables all the lights affecting the material.
  44582. */
  44583. _this._disableLighting = false;
  44584. /**
  44585. * Number of Simultaneous lights allowed on the material.
  44586. */
  44587. _this._maxSimultaneousLights = 4;
  44588. /**
  44589. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44590. */
  44591. _this._invertNormalMapX = false;
  44592. /**
  44593. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44594. */
  44595. _this._invertNormalMapY = false;
  44596. /**
  44597. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44598. */
  44599. _this._twoSidedLighting = false;
  44600. /**
  44601. * Defines the alpha limits in alpha test mode.
  44602. */
  44603. _this._alphaCutOff = 0.4;
  44604. /**
  44605. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44606. */
  44607. _this._forceAlphaTest = false;
  44608. /**
  44609. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44610. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44611. */
  44612. _this._useAlphaFresnel = false;
  44613. /**
  44614. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44615. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44616. */
  44617. _this._useLinearAlphaFresnel = false;
  44618. /**
  44619. * The transparency mode of the material.
  44620. */
  44621. _this._transparencyMode = null;
  44622. /**
  44623. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44624. * from cos thetav and roughness:
  44625. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44626. */
  44627. _this._environmentBRDFTexture = null;
  44628. /**
  44629. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44630. */
  44631. _this._forceIrradianceInFragment = false;
  44632. /**
  44633. * Force normal to face away from face.
  44634. */
  44635. _this._forceNormalForward = false;
  44636. /**
  44637. * Enables specular anti aliasing in the PBR shader.
  44638. * It will both interacts on the Geometry for analytical and IBL lighting.
  44639. * It also prefilter the roughness map based on the bump values.
  44640. */
  44641. _this._enableSpecularAntiAliasing = false;
  44642. /**
  44643. * Stores the available render targets.
  44644. */
  44645. _this._renderTargets = new BABYLON.SmartArray(16);
  44646. /**
  44647. * Sets the global ambient color for the material used in lighting calculations.
  44648. */
  44649. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44650. /**
  44651. * If set to true, no lighting calculations will be applied.
  44652. */
  44653. _this._unlit = false;
  44654. // Setup the default processing configuration to the scene.
  44655. _this._attachImageProcessingConfiguration(null);
  44656. _this.getRenderTargetTextures = function () {
  44657. _this._renderTargets.reset();
  44658. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44659. _this._renderTargets.push(_this._reflectionTexture);
  44660. }
  44661. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44662. _this._renderTargets.push(_this._refractionTexture);
  44663. }
  44664. return _this._renderTargets;
  44665. };
  44666. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44667. return _this;
  44668. }
  44669. /**
  44670. * Attaches a new image processing configuration to the PBR Material.
  44671. * @param configuration
  44672. */
  44673. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44674. var _this = this;
  44675. if (configuration === this._imageProcessingConfiguration) {
  44676. return;
  44677. }
  44678. // Detaches observer.
  44679. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44680. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44681. }
  44682. // Pick the scene configuration if needed.
  44683. if (!configuration) {
  44684. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44685. }
  44686. else {
  44687. this._imageProcessingConfiguration = configuration;
  44688. }
  44689. // Attaches observer.
  44690. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44691. _this._markAllSubMeshesAsImageProcessingDirty();
  44692. });
  44693. };
  44694. /**
  44695. * Gets the name of the material class.
  44696. */
  44697. PBRBaseMaterial.prototype.getClassName = function () {
  44698. return "PBRBaseMaterial";
  44699. };
  44700. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44701. /**
  44702. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44703. */
  44704. get: function () {
  44705. return this._useLogarithmicDepth;
  44706. },
  44707. /**
  44708. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44709. */
  44710. set: function (value) {
  44711. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44712. },
  44713. enumerable: true,
  44714. configurable: true
  44715. });
  44716. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44717. /**
  44718. * Gets the current transparency mode.
  44719. */
  44720. get: function () {
  44721. return this._transparencyMode;
  44722. },
  44723. /**
  44724. * Sets the transparency mode of the material.
  44725. */
  44726. set: function (value) {
  44727. if (this._transparencyMode === value) {
  44728. return;
  44729. }
  44730. this._transparencyMode = value;
  44731. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44732. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44733. },
  44734. enumerable: true,
  44735. configurable: true
  44736. });
  44737. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44738. /**
  44739. * Returns true if alpha blending should be disabled.
  44740. */
  44741. get: function () {
  44742. return (this._linkRefractionWithTransparency ||
  44743. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44744. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44745. },
  44746. enumerable: true,
  44747. configurable: true
  44748. });
  44749. /**
  44750. * Specifies whether or not this material should be rendered in alpha blend mode.
  44751. */
  44752. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44753. if (this._disableAlphaBlending) {
  44754. return false;
  44755. }
  44756. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44757. };
  44758. /**
  44759. * Specifies if the mesh will require alpha blending.
  44760. * @param mesh - BJS mesh.
  44761. */
  44762. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44763. if (this._disableAlphaBlending) {
  44764. return false;
  44765. }
  44766. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44767. };
  44768. /**
  44769. * Specifies whether or not this material should be rendered in alpha test mode.
  44770. */
  44771. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44772. if (this._forceAlphaTest) {
  44773. return true;
  44774. }
  44775. if (this._linkRefractionWithTransparency) {
  44776. return false;
  44777. }
  44778. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44779. };
  44780. /**
  44781. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44782. */
  44783. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44784. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44785. };
  44786. /**
  44787. * Gets the texture used for the alpha test.
  44788. */
  44789. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44790. return this._albedoTexture;
  44791. };
  44792. /**
  44793. * Specifies that the submesh is ready to be used.
  44794. * @param mesh - BJS mesh.
  44795. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44796. * @param useInstances - Specifies that instances should be used.
  44797. * @returns - boolean indicating that the submesh is ready or not.
  44798. */
  44799. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44800. if (subMesh.effect && this.isFrozen) {
  44801. if (this._wasPreviouslyReady) {
  44802. return true;
  44803. }
  44804. }
  44805. if (!subMesh._materialDefines) {
  44806. subMesh._materialDefines = new PBRMaterialDefines();
  44807. }
  44808. var defines = subMesh._materialDefines;
  44809. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44810. if (defines._renderId === this.getScene().getRenderId()) {
  44811. return true;
  44812. }
  44813. }
  44814. var scene = this.getScene();
  44815. var engine = scene.getEngine();
  44816. if (defines._areTexturesDirty) {
  44817. if (scene.texturesEnabled) {
  44818. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44819. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44820. return false;
  44821. }
  44822. }
  44823. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44824. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44825. return false;
  44826. }
  44827. }
  44828. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44829. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44830. return false;
  44831. }
  44832. }
  44833. var reflectionTexture = this._getReflectionTexture();
  44834. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44835. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44836. return false;
  44837. }
  44838. }
  44839. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44840. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44841. return false;
  44842. }
  44843. }
  44844. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44845. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44846. return false;
  44847. }
  44848. }
  44849. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44850. if (this._metallicTexture) {
  44851. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44852. return false;
  44853. }
  44854. }
  44855. else if (this._reflectivityTexture) {
  44856. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44857. return false;
  44858. }
  44859. }
  44860. if (this._microSurfaceTexture) {
  44861. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44862. return false;
  44863. }
  44864. }
  44865. }
  44866. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44867. // Bump texture cannot be not blocking.
  44868. if (!this._bumpTexture.isReady()) {
  44869. return false;
  44870. }
  44871. }
  44872. var refractionTexture = this._getRefractionTexture();
  44873. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44874. if (!refractionTexture.isReadyOrNotBlocking()) {
  44875. return false;
  44876. }
  44877. }
  44878. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44879. // This is blocking.
  44880. if (!this._environmentBRDFTexture.isReady()) {
  44881. return false;
  44882. }
  44883. }
  44884. }
  44885. }
  44886. if (defines._areImageProcessingDirty) {
  44887. if (!this._imageProcessingConfiguration.isReady()) {
  44888. return false;
  44889. }
  44890. }
  44891. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44892. mesh.createNormals(true);
  44893. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44894. }
  44895. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44896. if (effect) {
  44897. scene.resetCachedMaterial();
  44898. subMesh.setEffect(effect, defines);
  44899. this.buildUniformLayout();
  44900. }
  44901. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44902. return false;
  44903. }
  44904. defines._renderId = scene.getRenderId();
  44905. this._wasPreviouslyReady = true;
  44906. return true;
  44907. };
  44908. /**
  44909. * Specifies if the material uses metallic roughness workflow.
  44910. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44911. */
  44912. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44913. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44914. return true;
  44915. }
  44916. return false;
  44917. };
  44918. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44919. if (onCompiled === void 0) { onCompiled = null; }
  44920. if (onError === void 0) { onError = null; }
  44921. if (useInstances === void 0) { useInstances = null; }
  44922. if (useClipPlane === void 0) { useClipPlane = null; }
  44923. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44924. if (!defines.isDirty) {
  44925. return null;
  44926. }
  44927. defines.markAsProcessed();
  44928. var scene = this.getScene();
  44929. var engine = scene.getEngine();
  44930. // Fallbacks
  44931. var fallbacks = new BABYLON.EffectFallbacks();
  44932. var fallbackRank = 0;
  44933. if (defines.USESPHERICALINVERTEX) {
  44934. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44935. }
  44936. if (defines.FOG) {
  44937. fallbacks.addFallback(fallbackRank, "FOG");
  44938. }
  44939. if (defines.SPECULARAA) {
  44940. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44941. }
  44942. if (defines.POINTSIZE) {
  44943. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44944. }
  44945. if (defines.LOGARITHMICDEPTH) {
  44946. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44947. }
  44948. if (defines.PARALLAX) {
  44949. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44950. }
  44951. if (defines.PARALLAXOCCLUSION) {
  44952. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44953. }
  44954. if (defines.ENVIRONMENTBRDF) {
  44955. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44956. }
  44957. if (defines.TANGENT) {
  44958. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44959. }
  44960. if (defines.BUMP) {
  44961. fallbacks.addFallback(fallbackRank++, "BUMP");
  44962. }
  44963. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44964. if (defines.SPECULARTERM) {
  44965. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44966. }
  44967. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44968. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44969. }
  44970. if (defines.LIGHTMAP) {
  44971. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44972. }
  44973. if (defines.NORMAL) {
  44974. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44975. }
  44976. if (defines.AMBIENT) {
  44977. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44978. }
  44979. if (defines.EMISSIVE) {
  44980. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44981. }
  44982. if (defines.VERTEXCOLOR) {
  44983. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44984. }
  44985. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44986. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44987. }
  44988. if (defines.MORPHTARGETS) {
  44989. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44990. }
  44991. //Attributes
  44992. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44993. if (defines.NORMAL) {
  44994. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44995. }
  44996. if (defines.TANGENT) {
  44997. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44998. }
  44999. if (defines.UV1) {
  45000. attribs.push(BABYLON.VertexBuffer.UVKind);
  45001. }
  45002. if (defines.UV2) {
  45003. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45004. }
  45005. if (defines.VERTEXCOLOR) {
  45006. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45007. }
  45008. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45009. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45010. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45011. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45012. "vFogInfos", "vFogColor", "pointSize",
  45013. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45014. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45015. "mBones",
  45016. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45017. "vLightingIntensity",
  45018. "logarithmicDepthConstant",
  45019. "vSphericalX", "vSphericalY", "vSphericalZ",
  45020. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45021. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45022. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45023. "vTangentSpaceParams"
  45024. ];
  45025. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45026. "bumpSampler", "lightmapSampler", "opacitySampler",
  45027. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45028. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45029. "microSurfaceSampler", "environmentBrdfSampler"];
  45030. var uniformBuffers = ["Material", "Scene"];
  45031. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45032. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45033. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45034. uniformsNames: uniforms,
  45035. uniformBuffersNames: uniformBuffers,
  45036. samplers: samplers,
  45037. defines: defines,
  45038. maxSimultaneousLights: this._maxSimultaneousLights
  45039. });
  45040. var join = defines.toString();
  45041. return engine.createEffect("pbr", {
  45042. attributes: attribs,
  45043. uniformsNames: uniforms,
  45044. uniformBuffersNames: uniformBuffers,
  45045. samplers: samplers,
  45046. defines: join,
  45047. fallbacks: fallbacks,
  45048. onCompiled: onCompiled,
  45049. onError: onError,
  45050. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45051. }, engine);
  45052. };
  45053. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45054. if (useInstances === void 0) { useInstances = null; }
  45055. if (useClipPlane === void 0) { useClipPlane = null; }
  45056. var scene = this.getScene();
  45057. var engine = scene.getEngine();
  45058. // Lights
  45059. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45060. defines._needNormals = true;
  45061. // Textures
  45062. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45063. if (defines._areTexturesDirty) {
  45064. defines._needUVs = false;
  45065. if (scene.texturesEnabled) {
  45066. if (scene.getEngine().getCaps().textureLOD) {
  45067. defines.LODBASEDMICROSFURACE = true;
  45068. }
  45069. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45070. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45071. }
  45072. else {
  45073. defines.ALBEDO = false;
  45074. }
  45075. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45076. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45077. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45078. }
  45079. else {
  45080. defines.AMBIENT = false;
  45081. }
  45082. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45083. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45084. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45085. }
  45086. else {
  45087. defines.OPACITY = false;
  45088. }
  45089. var reflectionTexture = this._getReflectionTexture();
  45090. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45091. defines.REFLECTION = true;
  45092. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45093. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45094. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45095. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45096. defines.INVERTCUBICMAP = true;
  45097. }
  45098. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45099. switch (reflectionTexture.coordinatesMode) {
  45100. case BABYLON.Texture.EXPLICIT_MODE:
  45101. defines.REFLECTIONMAP_EXPLICIT = true;
  45102. break;
  45103. case BABYLON.Texture.PLANAR_MODE:
  45104. defines.REFLECTIONMAP_PLANAR = true;
  45105. break;
  45106. case BABYLON.Texture.PROJECTION_MODE:
  45107. defines.REFLECTIONMAP_PROJECTION = true;
  45108. break;
  45109. case BABYLON.Texture.SKYBOX_MODE:
  45110. defines.REFLECTIONMAP_SKYBOX = true;
  45111. break;
  45112. case BABYLON.Texture.SPHERICAL_MODE:
  45113. defines.REFLECTIONMAP_SPHERICAL = true;
  45114. break;
  45115. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45116. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45117. break;
  45118. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45119. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45120. break;
  45121. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45122. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45123. break;
  45124. case BABYLON.Texture.CUBIC_MODE:
  45125. case BABYLON.Texture.INVCUBIC_MODE:
  45126. default:
  45127. defines.REFLECTIONMAP_CUBIC = true;
  45128. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45129. break;
  45130. }
  45131. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45132. if (reflectionTexture.sphericalPolynomial) {
  45133. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45134. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45135. defines.USESPHERICALINVERTEX = false;
  45136. }
  45137. else {
  45138. defines.USESPHERICALINVERTEX = true;
  45139. }
  45140. }
  45141. }
  45142. }
  45143. else {
  45144. defines.REFLECTION = false;
  45145. defines.REFLECTIONMAP_3D = false;
  45146. defines.REFLECTIONMAP_SPHERICAL = false;
  45147. defines.REFLECTIONMAP_PLANAR = false;
  45148. defines.REFLECTIONMAP_CUBIC = false;
  45149. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45150. defines.REFLECTIONMAP_PROJECTION = false;
  45151. defines.REFLECTIONMAP_SKYBOX = false;
  45152. defines.REFLECTIONMAP_EXPLICIT = false;
  45153. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45154. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45155. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45156. defines.INVERTCUBICMAP = false;
  45157. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45158. defines.USESPHERICALINVERTEX = false;
  45159. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45160. defines.LODINREFLECTIONALPHA = false;
  45161. defines.GAMMAREFLECTION = false;
  45162. }
  45163. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45164. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45165. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45166. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45167. }
  45168. else {
  45169. defines.LIGHTMAP = false;
  45170. }
  45171. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45173. }
  45174. else {
  45175. defines.EMISSIVE = false;
  45176. }
  45177. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45178. if (this._metallicTexture) {
  45179. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45180. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45181. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45182. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45183. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45184. }
  45185. else if (this._reflectivityTexture) {
  45186. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45187. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45188. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45189. }
  45190. else {
  45191. defines.REFLECTIVITY = false;
  45192. }
  45193. if (this._microSurfaceTexture) {
  45194. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45195. }
  45196. else {
  45197. defines.MICROSURFACEMAP = false;
  45198. }
  45199. }
  45200. else {
  45201. defines.REFLECTIVITY = false;
  45202. defines.MICROSURFACEMAP = false;
  45203. }
  45204. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45205. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45206. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45207. defines.PARALLAX = true;
  45208. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45209. }
  45210. else {
  45211. defines.PARALLAX = false;
  45212. }
  45213. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45214. }
  45215. else {
  45216. defines.BUMP = false;
  45217. }
  45218. var refractionTexture = this._getRefractionTexture();
  45219. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45220. defines.REFRACTION = true;
  45221. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45222. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45223. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45224. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45225. if (this._linkRefractionWithTransparency) {
  45226. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45227. }
  45228. }
  45229. else {
  45230. defines.REFRACTION = false;
  45231. }
  45232. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45233. defines.ENVIRONMENTBRDF = true;
  45234. }
  45235. else {
  45236. defines.ENVIRONMENTBRDF = false;
  45237. }
  45238. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45239. defines.ALPHAFROMALBEDO = true;
  45240. }
  45241. else {
  45242. defines.ALPHAFROMALBEDO = false;
  45243. }
  45244. }
  45245. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45246. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45247. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45248. if (!this.backFaceCulling && this._twoSidedLighting) {
  45249. defines.TWOSIDEDLIGHTING = true;
  45250. }
  45251. else {
  45252. defines.TWOSIDEDLIGHTING = false;
  45253. }
  45254. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45255. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45256. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45257. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45258. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45259. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45260. }
  45261. if (defines._areImageProcessingDirty) {
  45262. this._imageProcessingConfiguration.prepareDefines(defines);
  45263. }
  45264. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45265. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45266. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45267. // Misc.
  45268. if (defines._areMiscDirty) {
  45269. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45270. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45271. }
  45272. // Values that need to be evaluated on every frame
  45273. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45274. // Attribs
  45275. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45276. };
  45277. /**
  45278. * Force shader compilation
  45279. */
  45280. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45281. var _this = this;
  45282. var localOptions = __assign({ clipPlane: false }, options);
  45283. var defines = new PBRMaterialDefines();
  45284. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45285. if (effect.isReady()) {
  45286. if (onCompiled) {
  45287. onCompiled(this);
  45288. }
  45289. }
  45290. else {
  45291. effect.onCompileObservable.add(function () {
  45292. if (onCompiled) {
  45293. onCompiled(_this);
  45294. }
  45295. });
  45296. }
  45297. };
  45298. /**
  45299. * Initializes the uniform buffer layout for the shader.
  45300. */
  45301. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45302. // Order is important !
  45303. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45304. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45305. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45306. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45307. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45308. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45309. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45310. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45311. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45312. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45313. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45314. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45315. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45316. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45317. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45318. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45319. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45320. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45321. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45322. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45323. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45324. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45325. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45326. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45327. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45328. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45329. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45330. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45331. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45332. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45333. this._uniformBuffer.addUniform("pointSize", 1);
  45334. this._uniformBuffer.create();
  45335. };
  45336. /**
  45337. * Unbinds the textures.
  45338. */
  45339. PBRBaseMaterial.prototype.unbind = function () {
  45340. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45341. this._uniformBuffer.setTexture("reflectionSampler", null);
  45342. }
  45343. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45344. this._uniformBuffer.setTexture("refractionSampler", null);
  45345. }
  45346. _super.prototype.unbind.call(this);
  45347. };
  45348. /**
  45349. * Binds the submesh data.
  45350. * @param world - The world matrix.
  45351. * @param mesh - The BJS mesh.
  45352. * @param subMesh - A submesh of the BJS mesh.
  45353. */
  45354. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45355. var scene = this.getScene();
  45356. var defines = subMesh._materialDefines;
  45357. if (!defines) {
  45358. return;
  45359. }
  45360. var effect = subMesh.effect;
  45361. if (!effect) {
  45362. return;
  45363. }
  45364. this._activeEffect = effect;
  45365. // Matrices
  45366. this.bindOnlyWorldMatrix(world);
  45367. // Normal Matrix
  45368. if (defines.OBJECTSPACE_NORMALMAP) {
  45369. world.toNormalMatrix(this._normalMatrix);
  45370. this.bindOnlyNormalMatrix(this._normalMatrix);
  45371. }
  45372. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45373. // Bones
  45374. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45375. var reflectionTexture = null;
  45376. if (mustRebind) {
  45377. this._uniformBuffer.bindToEffect(effect, "Material");
  45378. this.bindViewProjection(effect);
  45379. reflectionTexture = this._getReflectionTexture();
  45380. var refractionTexture = this._getRefractionTexture();
  45381. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45382. // Texture uniforms
  45383. if (scene.texturesEnabled) {
  45384. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45385. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45386. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45387. }
  45388. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45389. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45390. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45391. }
  45392. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45393. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45394. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45395. }
  45396. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45397. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45398. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45399. if (reflectionTexture.boundingBoxSize) {
  45400. var cubeTexture = reflectionTexture;
  45401. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45402. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45403. }
  45404. var polynomials = reflectionTexture.sphericalPolynomial;
  45405. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45406. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45407. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45408. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45409. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45410. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45411. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45412. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45413. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45414. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45415. }
  45416. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45417. }
  45418. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45419. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45420. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45421. }
  45422. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45423. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45424. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45425. }
  45426. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45427. if (this._metallicTexture) {
  45428. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45429. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45430. }
  45431. else if (this._reflectivityTexture) {
  45432. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45433. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45434. }
  45435. if (this._microSurfaceTexture) {
  45436. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45437. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45438. }
  45439. }
  45440. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45441. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45442. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45443. if (scene._mirroredCameraPosition) {
  45444. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45445. }
  45446. else {
  45447. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45448. }
  45449. }
  45450. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45451. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45452. var depth = 1.0;
  45453. if (!refractionTexture.isCube) {
  45454. if (refractionTexture.depth) {
  45455. depth = refractionTexture.depth;
  45456. }
  45457. }
  45458. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45459. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45460. }
  45461. }
  45462. // Point size
  45463. if (this.pointsCloud) {
  45464. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45465. }
  45466. // Colors
  45467. if (defines.METALLICWORKFLOW) {
  45468. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45469. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45470. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45471. }
  45472. else {
  45473. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45474. }
  45475. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45476. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45477. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45478. // Misc
  45479. this._lightingInfos.x = this._directIntensity;
  45480. this._lightingInfos.y = this._emissiveIntensity;
  45481. this._lightingInfos.z = this._environmentIntensity;
  45482. this._lightingInfos.w = this._specularIntensity;
  45483. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45484. }
  45485. // Textures
  45486. if (scene.texturesEnabled) {
  45487. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45488. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45489. }
  45490. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45491. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45492. }
  45493. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45494. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45495. }
  45496. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45497. if (defines.LODBASEDMICROSFURACE) {
  45498. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45499. }
  45500. else {
  45501. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45502. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45503. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45504. }
  45505. }
  45506. if (defines.ENVIRONMENTBRDF) {
  45507. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45508. }
  45509. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45510. if (defines.LODBASEDMICROSFURACE) {
  45511. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45512. }
  45513. else {
  45514. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45515. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45516. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45517. }
  45518. }
  45519. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45520. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45521. }
  45522. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45523. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45524. }
  45525. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45526. if (this._metallicTexture) {
  45527. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45528. }
  45529. else if (this._reflectivityTexture) {
  45530. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45531. }
  45532. if (this._microSurfaceTexture) {
  45533. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45534. }
  45535. }
  45536. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45537. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45538. }
  45539. }
  45540. // Clip plane
  45541. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45542. // Colors
  45543. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45544. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45545. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45546. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45547. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45548. }
  45549. if (mustRebind || !this.isFrozen) {
  45550. // Lights
  45551. if (scene.lightsEnabled && !this._disableLighting) {
  45552. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45553. }
  45554. // View
  45555. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45556. this.bindView(effect);
  45557. }
  45558. // Fog
  45559. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45560. // Morph targets
  45561. if (defines.NUM_MORPH_INFLUENCERS) {
  45562. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45563. }
  45564. // image processing
  45565. this._imageProcessingConfiguration.bind(this._activeEffect);
  45566. // Log. depth
  45567. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45568. }
  45569. this._uniformBuffer.update();
  45570. this._afterBind(mesh, this._activeEffect);
  45571. };
  45572. /**
  45573. * Returns the animatable textures.
  45574. * @returns - Array of animatable textures.
  45575. */
  45576. PBRBaseMaterial.prototype.getAnimatables = function () {
  45577. var results = [];
  45578. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45579. results.push(this._albedoTexture);
  45580. }
  45581. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45582. results.push(this._ambientTexture);
  45583. }
  45584. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45585. results.push(this._opacityTexture);
  45586. }
  45587. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45588. results.push(this._reflectionTexture);
  45589. }
  45590. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45591. results.push(this._emissiveTexture);
  45592. }
  45593. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45594. results.push(this._metallicTexture);
  45595. }
  45596. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45597. results.push(this._reflectivityTexture);
  45598. }
  45599. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45600. results.push(this._bumpTexture);
  45601. }
  45602. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45603. results.push(this._lightmapTexture);
  45604. }
  45605. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45606. results.push(this._refractionTexture);
  45607. }
  45608. return results;
  45609. };
  45610. /**
  45611. * Returns the texture used for reflections.
  45612. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45613. */
  45614. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45615. if (this._reflectionTexture) {
  45616. return this._reflectionTexture;
  45617. }
  45618. return this.getScene().environmentTexture;
  45619. };
  45620. /**
  45621. * Returns the texture used for refraction or null if none is used.
  45622. * @returns - Refection texture if present. If no refraction texture and refraction
  45623. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45624. */
  45625. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45626. if (this._refractionTexture) {
  45627. return this._refractionTexture;
  45628. }
  45629. if (this._linkRefractionWithTransparency) {
  45630. return this.getScene().environmentTexture;
  45631. }
  45632. return null;
  45633. };
  45634. /**
  45635. * Disposes the resources of the material.
  45636. * @param forceDisposeEffect - Forces the disposal of effects.
  45637. * @param forceDisposeTextures - Forces the disposal of all textures.
  45638. */
  45639. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45640. if (forceDisposeTextures) {
  45641. if (this._albedoTexture) {
  45642. this._albedoTexture.dispose();
  45643. }
  45644. if (this._ambientTexture) {
  45645. this._ambientTexture.dispose();
  45646. }
  45647. if (this._opacityTexture) {
  45648. this._opacityTexture.dispose();
  45649. }
  45650. if (this._reflectionTexture) {
  45651. this._reflectionTexture.dispose();
  45652. }
  45653. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45654. this._environmentBRDFTexture.dispose();
  45655. }
  45656. if (this._emissiveTexture) {
  45657. this._emissiveTexture.dispose();
  45658. }
  45659. if (this._metallicTexture) {
  45660. this._metallicTexture.dispose();
  45661. }
  45662. if (this._reflectivityTexture) {
  45663. this._reflectivityTexture.dispose();
  45664. }
  45665. if (this._bumpTexture) {
  45666. this._bumpTexture.dispose();
  45667. }
  45668. if (this._lightmapTexture) {
  45669. this._lightmapTexture.dispose();
  45670. }
  45671. if (this._refractionTexture) {
  45672. this._refractionTexture.dispose();
  45673. }
  45674. }
  45675. this._renderTargets.dispose();
  45676. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45677. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45678. }
  45679. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45680. };
  45681. /**
  45682. * Stores the reflectivity values based on metallic roughness workflow.
  45683. */
  45684. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45685. __decorate([
  45686. BABYLON.serializeAsImageProcessingConfiguration()
  45687. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45688. __decorate([
  45689. BABYLON.serialize()
  45690. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45691. __decorate([
  45692. BABYLON.serialize()
  45693. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45694. return PBRBaseMaterial;
  45695. }(BABYLON.PushMaterial));
  45696. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45697. })(BABYLON || (BABYLON = {}));
  45698. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45699. var BABYLON;
  45700. (function (BABYLON) {
  45701. /**
  45702. * The Physically based simple base material of BJS.
  45703. *
  45704. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45705. * It is used as the base class for both the specGloss and metalRough conventions.
  45706. */
  45707. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45708. __extends(PBRBaseSimpleMaterial, _super);
  45709. /**
  45710. * Instantiates a new PBRMaterial instance.
  45711. *
  45712. * @param name The material name
  45713. * @param scene The scene the material will be use in.
  45714. */
  45715. function PBRBaseSimpleMaterial(name, scene) {
  45716. var _this = _super.call(this, name, scene) || this;
  45717. /**
  45718. * Number of Simultaneous lights allowed on the material.
  45719. */
  45720. _this.maxSimultaneousLights = 4;
  45721. /**
  45722. * If sets to true, disables all the lights affecting the material.
  45723. */
  45724. _this.disableLighting = false;
  45725. /**
  45726. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45727. */
  45728. _this.invertNormalMapX = false;
  45729. /**
  45730. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45731. */
  45732. _this.invertNormalMapY = false;
  45733. /**
  45734. * Emissivie color used to self-illuminate the model.
  45735. */
  45736. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45737. /**
  45738. * Occlusion Channel Strenght.
  45739. */
  45740. _this.occlusionStrength = 1.0;
  45741. _this.useLightmapAsShadowmap = false;
  45742. _this._useAlphaFromAlbedoTexture = true;
  45743. _this._useAmbientInGrayScale = true;
  45744. return _this;
  45745. }
  45746. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45747. /**
  45748. * Gets the current double sided mode.
  45749. */
  45750. get: function () {
  45751. return this._twoSidedLighting;
  45752. },
  45753. /**
  45754. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45755. */
  45756. set: function (value) {
  45757. if (this._twoSidedLighting === value) {
  45758. return;
  45759. }
  45760. this._twoSidedLighting = value;
  45761. this.backFaceCulling = !value;
  45762. this._markAllSubMeshesAsTexturesDirty();
  45763. },
  45764. enumerable: true,
  45765. configurable: true
  45766. });
  45767. /**
  45768. * Return the active textures of the material.
  45769. */
  45770. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45771. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45772. if (this.environmentTexture) {
  45773. activeTextures.push(this.environmentTexture);
  45774. }
  45775. if (this.normalTexture) {
  45776. activeTextures.push(this.normalTexture);
  45777. }
  45778. if (this.emissiveTexture) {
  45779. activeTextures.push(this.emissiveTexture);
  45780. }
  45781. if (this.occlusionTexture) {
  45782. activeTextures.push(this.occlusionTexture);
  45783. }
  45784. if (this.lightmapTexture) {
  45785. activeTextures.push(this.lightmapTexture);
  45786. }
  45787. return activeTextures;
  45788. };
  45789. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45790. if (_super.prototype.hasTexture.call(this, texture)) {
  45791. return true;
  45792. }
  45793. if (this.lightmapTexture === texture) {
  45794. return true;
  45795. }
  45796. return false;
  45797. };
  45798. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45799. return "PBRBaseSimpleMaterial";
  45800. };
  45801. __decorate([
  45802. BABYLON.serialize(),
  45803. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45804. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45805. __decorate([
  45806. BABYLON.serialize(),
  45807. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45808. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45809. __decorate([
  45810. BABYLON.serializeAsTexture(),
  45811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45812. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45813. __decorate([
  45814. BABYLON.serialize(),
  45815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45816. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45817. __decorate([
  45818. BABYLON.serialize(),
  45819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45820. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45821. __decorate([
  45822. BABYLON.serializeAsTexture(),
  45823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45824. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45825. __decorate([
  45826. BABYLON.serializeAsColor3("emissive"),
  45827. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45828. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45829. __decorate([
  45830. BABYLON.serializeAsTexture(),
  45831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45832. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45833. __decorate([
  45834. BABYLON.serialize(),
  45835. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45836. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45837. __decorate([
  45838. BABYLON.serializeAsTexture(),
  45839. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45840. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45844. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45845. __decorate([
  45846. BABYLON.serialize()
  45847. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45848. __decorate([
  45849. BABYLON.serializeAsTexture(),
  45850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45851. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45852. __decorate([
  45853. BABYLON.serialize(),
  45854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45855. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45856. return PBRBaseSimpleMaterial;
  45857. }(BABYLON.PBRBaseMaterial));
  45858. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45859. })(BABYLON || (BABYLON = {}));
  45860. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45861. var BABYLON;
  45862. (function (BABYLON) {
  45863. /**
  45864. * The Physically based material of BJS.
  45865. *
  45866. * This offers the main features of a standard PBR material.
  45867. * For more information, please refer to the documentation :
  45868. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45869. */
  45870. var PBRMaterial = /** @class */ (function (_super) {
  45871. __extends(PBRMaterial, _super);
  45872. /**
  45873. * Instantiates a new PBRMaterial instance.
  45874. *
  45875. * @param name The material name
  45876. * @param scene The scene the material will be use in.
  45877. */
  45878. function PBRMaterial(name, scene) {
  45879. var _this = _super.call(this, name, scene) || this;
  45880. /**
  45881. * Intensity of the direct lights e.g. the four lights available in your scene.
  45882. * This impacts both the direct diffuse and specular highlights.
  45883. */
  45884. _this.directIntensity = 1.0;
  45885. /**
  45886. * Intensity of the emissive part of the material.
  45887. * This helps controlling the emissive effect without modifying the emissive color.
  45888. */
  45889. _this.emissiveIntensity = 1.0;
  45890. /**
  45891. * Intensity of the environment e.g. how much the environment will light the object
  45892. * either through harmonics for rough material or through the refelction for shiny ones.
  45893. */
  45894. _this.environmentIntensity = 1.0;
  45895. /**
  45896. * This is a special control allowing the reduction of the specular highlights coming from the
  45897. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45898. */
  45899. _this.specularIntensity = 1.0;
  45900. /**
  45901. * Debug Control allowing disabling the bump map on this material.
  45902. */
  45903. _this.disableBumpMap = false;
  45904. /**
  45905. * AKA Occlusion Texture Intensity in other nomenclature.
  45906. */
  45907. _this.ambientTextureStrength = 1.0;
  45908. /**
  45909. * The color of a material in ambient lighting.
  45910. */
  45911. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45912. /**
  45913. * AKA Diffuse Color in other nomenclature.
  45914. */
  45915. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45916. /**
  45917. * AKA Specular Color in other nomenclature.
  45918. */
  45919. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45920. /**
  45921. * The color reflected from the material.
  45922. */
  45923. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45924. /**
  45925. * The color emitted from the material.
  45926. */
  45927. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45928. /**
  45929. * AKA Glossiness in other nomenclature.
  45930. */
  45931. _this.microSurface = 1.0;
  45932. /**
  45933. * source material index of refraction (IOR)' / 'destination material IOR.
  45934. */
  45935. _this.indexOfRefraction = 0.66;
  45936. /**
  45937. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45938. */
  45939. _this.invertRefractionY = false;
  45940. /**
  45941. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45942. * Materials half opaque for instance using refraction could benefit from this control.
  45943. */
  45944. _this.linkRefractionWithTransparency = false;
  45945. _this.useLightmapAsShadowmap = false;
  45946. /**
  45947. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45948. */
  45949. _this.useAlphaFromAlbedoTexture = false;
  45950. /**
  45951. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45952. */
  45953. _this.forceAlphaTest = false;
  45954. /**
  45955. * Defines the alpha limits in alpha test mode.
  45956. */
  45957. _this.alphaCutOff = 0.4;
  45958. /**
  45959. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45960. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45961. */
  45962. _this.useSpecularOverAlpha = true;
  45963. /**
  45964. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45965. */
  45966. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45967. /**
  45968. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45969. */
  45970. _this.useRoughnessFromMetallicTextureAlpha = true;
  45971. /**
  45972. * Specifies if the metallic texture contains the roughness information in its green channel.
  45973. */
  45974. _this.useRoughnessFromMetallicTextureGreen = false;
  45975. /**
  45976. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45977. */
  45978. _this.useMetallnessFromMetallicTextureBlue = false;
  45979. /**
  45980. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45981. */
  45982. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45983. /**
  45984. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45985. */
  45986. _this.useAmbientInGrayScale = false;
  45987. /**
  45988. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45989. * The material will try to infer what glossiness each pixel should be.
  45990. */
  45991. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45992. /**
  45993. * BJS is using an harcoded light falloff based on a manually sets up range.
  45994. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45995. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45996. */
  45997. _this.usePhysicalLightFalloff = true;
  45998. /**
  45999. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46000. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46001. */
  46002. _this.useRadianceOverAlpha = true;
  46003. /**
  46004. * Allows using an object space normal map (instead of tangent space).
  46005. */
  46006. _this.useObjectSpaceNormalMap = false;
  46007. /**
  46008. * Allows using the bump map in parallax mode.
  46009. */
  46010. _this.useParallax = false;
  46011. /**
  46012. * Allows using the bump map in parallax occlusion mode.
  46013. */
  46014. _this.useParallaxOcclusion = false;
  46015. /**
  46016. * Controls the scale bias of the parallax mode.
  46017. */
  46018. _this.parallaxScaleBias = 0.05;
  46019. /**
  46020. * If sets to true, disables all the lights affecting the material.
  46021. */
  46022. _this.disableLighting = false;
  46023. /**
  46024. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46025. */
  46026. _this.forceIrradianceInFragment = false;
  46027. /**
  46028. * Number of Simultaneous lights allowed on the material.
  46029. */
  46030. _this.maxSimultaneousLights = 4;
  46031. /**
  46032. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46033. */
  46034. _this.invertNormalMapX = false;
  46035. /**
  46036. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46037. */
  46038. _this.invertNormalMapY = false;
  46039. /**
  46040. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46041. */
  46042. _this.twoSidedLighting = false;
  46043. /**
  46044. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46045. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46046. */
  46047. _this.useAlphaFresnel = false;
  46048. /**
  46049. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46050. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46051. */
  46052. _this.useLinearAlphaFresnel = false;
  46053. /**
  46054. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46055. * And/Or occlude the blended part.
  46056. */
  46057. _this.environmentBRDFTexture = null;
  46058. /**
  46059. * Force normal to face away from face.
  46060. */
  46061. _this.forceNormalForward = false;
  46062. /**
  46063. * Enables specular anti aliasing in the PBR shader.
  46064. * It will both interacts on the Geometry for analytical and IBL lighting.
  46065. * It also prefilter the roughness map based on the bump values.
  46066. */
  46067. _this.enableSpecularAntiAliasing = false;
  46068. /**
  46069. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46070. * makes the reflect vector face the model (under horizon).
  46071. */
  46072. _this.useHorizonOcclusion = true;
  46073. /**
  46074. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46075. * too much the area relying on ambient texture to define their ambient occlusion.
  46076. */
  46077. _this.useRadianceOcclusion = true;
  46078. /**
  46079. * If set to true, no lighting calculations will be applied.
  46080. */
  46081. _this.unlit = false;
  46082. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46083. return _this;
  46084. }
  46085. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46086. /**
  46087. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46088. */
  46089. get: function () {
  46090. return this._PBRMATERIAL_OPAQUE;
  46091. },
  46092. enumerable: true,
  46093. configurable: true
  46094. });
  46095. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46096. /**
  46097. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46098. */
  46099. get: function () {
  46100. return this._PBRMATERIAL_ALPHATEST;
  46101. },
  46102. enumerable: true,
  46103. configurable: true
  46104. });
  46105. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46106. /**
  46107. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46108. */
  46109. get: function () {
  46110. return this._PBRMATERIAL_ALPHABLEND;
  46111. },
  46112. enumerable: true,
  46113. configurable: true
  46114. });
  46115. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46116. /**
  46117. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46118. * They are also discarded below the alpha cutoff threshold to improve performances.
  46119. */
  46120. get: function () {
  46121. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46122. },
  46123. enumerable: true,
  46124. configurable: true
  46125. });
  46126. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46127. /**
  46128. * Gets the image processing configuration used either in this material.
  46129. */
  46130. get: function () {
  46131. return this._imageProcessingConfiguration;
  46132. },
  46133. /**
  46134. * Sets the Default image processing configuration used either in the this material.
  46135. *
  46136. * If sets to null, the scene one is in use.
  46137. */
  46138. set: function (value) {
  46139. this._attachImageProcessingConfiguration(value);
  46140. // Ensure the effect will be rebuilt.
  46141. this._markAllSubMeshesAsTexturesDirty();
  46142. },
  46143. enumerable: true,
  46144. configurable: true
  46145. });
  46146. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46147. /**
  46148. * Gets wether the color curves effect is enabled.
  46149. */
  46150. get: function () {
  46151. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46152. },
  46153. /**
  46154. * Sets wether the color curves effect is enabled.
  46155. */
  46156. set: function (value) {
  46157. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46163. /**
  46164. * Gets wether the color grading effect is enabled.
  46165. */
  46166. get: function () {
  46167. return this.imageProcessingConfiguration.colorGradingEnabled;
  46168. },
  46169. /**
  46170. * Gets wether the color grading effect is enabled.
  46171. */
  46172. set: function (value) {
  46173. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46174. },
  46175. enumerable: true,
  46176. configurable: true
  46177. });
  46178. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46179. /**
  46180. * Gets wether tonemapping is enabled or not.
  46181. */
  46182. get: function () {
  46183. return this._imageProcessingConfiguration.toneMappingEnabled;
  46184. },
  46185. /**
  46186. * Sets wether tonemapping is enabled or not
  46187. */
  46188. set: function (value) {
  46189. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46190. },
  46191. enumerable: true,
  46192. configurable: true
  46193. });
  46194. ;
  46195. ;
  46196. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46197. /**
  46198. * The camera exposure used on this material.
  46199. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46200. * This corresponds to a photographic exposure.
  46201. */
  46202. get: function () {
  46203. return this._imageProcessingConfiguration.exposure;
  46204. },
  46205. /**
  46206. * The camera exposure used on this material.
  46207. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46208. * This corresponds to a photographic exposure.
  46209. */
  46210. set: function (value) {
  46211. this._imageProcessingConfiguration.exposure = value;
  46212. },
  46213. enumerable: true,
  46214. configurable: true
  46215. });
  46216. ;
  46217. ;
  46218. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46219. /**
  46220. * Gets The camera contrast used on this material.
  46221. */
  46222. get: function () {
  46223. return this._imageProcessingConfiguration.contrast;
  46224. },
  46225. /**
  46226. * Sets The camera contrast used on this material.
  46227. */
  46228. set: function (value) {
  46229. this._imageProcessingConfiguration.contrast = value;
  46230. },
  46231. enumerable: true,
  46232. configurable: true
  46233. });
  46234. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46235. /**
  46236. * Gets the Color Grading 2D Lookup Texture.
  46237. */
  46238. get: function () {
  46239. return this._imageProcessingConfiguration.colorGradingTexture;
  46240. },
  46241. /**
  46242. * Sets the Color Grading 2D Lookup Texture.
  46243. */
  46244. set: function (value) {
  46245. this._imageProcessingConfiguration.colorGradingTexture = value;
  46246. },
  46247. enumerable: true,
  46248. configurable: true
  46249. });
  46250. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46251. /**
  46252. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46253. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46254. * 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;
  46255. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46256. */
  46257. get: function () {
  46258. return this._imageProcessingConfiguration.colorCurves;
  46259. },
  46260. /**
  46261. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46262. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46263. * 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;
  46264. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46265. */
  46266. set: function (value) {
  46267. this._imageProcessingConfiguration.colorCurves = value;
  46268. },
  46269. enumerable: true,
  46270. configurable: true
  46271. });
  46272. /**
  46273. * Returns the name of this material class.
  46274. */
  46275. PBRMaterial.prototype.getClassName = function () {
  46276. return "PBRMaterial";
  46277. };
  46278. /**
  46279. * Returns an array of the actively used textures.
  46280. * @returns - Array of BaseTextures
  46281. */
  46282. PBRMaterial.prototype.getActiveTextures = function () {
  46283. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46284. if (this._albedoTexture) {
  46285. activeTextures.push(this._albedoTexture);
  46286. }
  46287. if (this._ambientTexture) {
  46288. activeTextures.push(this._ambientTexture);
  46289. }
  46290. if (this._opacityTexture) {
  46291. activeTextures.push(this._opacityTexture);
  46292. }
  46293. if (this._reflectionTexture) {
  46294. activeTextures.push(this._reflectionTexture);
  46295. }
  46296. if (this._emissiveTexture) {
  46297. activeTextures.push(this._emissiveTexture);
  46298. }
  46299. if (this._reflectivityTexture) {
  46300. activeTextures.push(this._reflectivityTexture);
  46301. }
  46302. if (this._metallicTexture) {
  46303. activeTextures.push(this._metallicTexture);
  46304. }
  46305. if (this._microSurfaceTexture) {
  46306. activeTextures.push(this._microSurfaceTexture);
  46307. }
  46308. if (this._bumpTexture) {
  46309. activeTextures.push(this._bumpTexture);
  46310. }
  46311. if (this._lightmapTexture) {
  46312. activeTextures.push(this._lightmapTexture);
  46313. }
  46314. if (this._refractionTexture) {
  46315. activeTextures.push(this._refractionTexture);
  46316. }
  46317. return activeTextures;
  46318. };
  46319. /**
  46320. * Checks to see if a texture is used in the material.
  46321. * @param texture - Base texture to use.
  46322. * @returns - Boolean specifying if a texture is used in the material.
  46323. */
  46324. PBRMaterial.prototype.hasTexture = function (texture) {
  46325. if (_super.prototype.hasTexture.call(this, texture)) {
  46326. return true;
  46327. }
  46328. if (this._albedoTexture === texture) {
  46329. return true;
  46330. }
  46331. if (this._ambientTexture === texture) {
  46332. return true;
  46333. }
  46334. if (this._opacityTexture === texture) {
  46335. return true;
  46336. }
  46337. if (this._reflectionTexture === texture) {
  46338. return true;
  46339. }
  46340. if (this._reflectivityTexture === texture) {
  46341. return true;
  46342. }
  46343. if (this._metallicTexture === texture) {
  46344. return true;
  46345. }
  46346. if (this._microSurfaceTexture === texture) {
  46347. return true;
  46348. }
  46349. if (this._bumpTexture === texture) {
  46350. return true;
  46351. }
  46352. if (this._lightmapTexture === texture) {
  46353. return true;
  46354. }
  46355. if (this._refractionTexture === texture) {
  46356. return true;
  46357. }
  46358. return false;
  46359. };
  46360. /**
  46361. * Makes a duplicate of the current material.
  46362. * @param name - name to use for the new material.
  46363. */
  46364. PBRMaterial.prototype.clone = function (name) {
  46365. var _this = this;
  46366. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46367. clone.id = name;
  46368. clone.name = name;
  46369. return clone;
  46370. };
  46371. /**
  46372. * Serializes this PBR Material.
  46373. * @returns - An object with the serialized material.
  46374. */
  46375. PBRMaterial.prototype.serialize = function () {
  46376. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46377. serializationObject.customType = "BABYLON.PBRMaterial";
  46378. return serializationObject;
  46379. };
  46380. // Statics
  46381. /**
  46382. * Parses a PBR Material from a serialized object.
  46383. * @param source - Serialized object.
  46384. * @param scene - BJS scene instance.
  46385. * @param rootUrl - url for the scene object
  46386. * @returns - PBRMaterial
  46387. */
  46388. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46389. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46390. };
  46391. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46392. /**
  46393. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46394. */
  46395. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46396. /**
  46397. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46398. */
  46399. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46400. /**
  46401. * 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.
  46402. * They are also discarded below the alpha cutoff threshold to improve performances.
  46403. */
  46404. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46405. __decorate([
  46406. BABYLON.serialize(),
  46407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46408. ], PBRMaterial.prototype, "directIntensity", void 0);
  46409. __decorate([
  46410. BABYLON.serialize(),
  46411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46412. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46413. __decorate([
  46414. BABYLON.serialize(),
  46415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46416. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46417. __decorate([
  46418. BABYLON.serialize(),
  46419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46420. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46421. __decorate([
  46422. BABYLON.serialize(),
  46423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46424. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46425. __decorate([
  46426. BABYLON.serializeAsTexture(),
  46427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46428. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46429. __decorate([
  46430. BABYLON.serializeAsTexture(),
  46431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46432. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46433. __decorate([
  46434. BABYLON.serialize(),
  46435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46436. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46437. __decorate([
  46438. BABYLON.serializeAsTexture(),
  46439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46440. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46441. __decorate([
  46442. BABYLON.serializeAsTexture(),
  46443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46444. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46445. __decorate([
  46446. BABYLON.serializeAsTexture(),
  46447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46448. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46449. __decorate([
  46450. BABYLON.serializeAsTexture(),
  46451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46452. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46453. __decorate([
  46454. BABYLON.serializeAsTexture(),
  46455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46456. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46457. __decorate([
  46458. BABYLON.serialize(),
  46459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46460. ], PBRMaterial.prototype, "metallic", void 0);
  46461. __decorate([
  46462. BABYLON.serialize(),
  46463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46464. ], PBRMaterial.prototype, "roughness", void 0);
  46465. __decorate([
  46466. BABYLON.serializeAsTexture(),
  46467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46468. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46469. __decorate([
  46470. BABYLON.serializeAsTexture(),
  46471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46472. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46473. __decorate([
  46474. BABYLON.serializeAsTexture(),
  46475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46476. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46477. __decorate([
  46478. BABYLON.serializeAsTexture(),
  46479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46480. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46481. __decorate([
  46482. BABYLON.serializeAsColor3("ambient"),
  46483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46484. ], PBRMaterial.prototype, "ambientColor", void 0);
  46485. __decorate([
  46486. BABYLON.serializeAsColor3("albedo"),
  46487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46488. ], PBRMaterial.prototype, "albedoColor", void 0);
  46489. __decorate([
  46490. BABYLON.serializeAsColor3("reflectivity"),
  46491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46492. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46493. __decorate([
  46494. BABYLON.serializeAsColor3("reflection"),
  46495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46496. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46497. __decorate([
  46498. BABYLON.serializeAsColor3("emissive"),
  46499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46500. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46501. __decorate([
  46502. BABYLON.serialize(),
  46503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46504. ], PBRMaterial.prototype, "microSurface", void 0);
  46505. __decorate([
  46506. BABYLON.serialize(),
  46507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46508. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46509. __decorate([
  46510. BABYLON.serialize(),
  46511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46512. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46513. __decorate([
  46514. BABYLON.serialize(),
  46515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46516. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46517. __decorate([
  46518. BABYLON.serialize(),
  46519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46520. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46521. __decorate([
  46522. BABYLON.serialize(),
  46523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46524. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46525. __decorate([
  46526. BABYLON.serialize(),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46528. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46529. __decorate([
  46530. BABYLON.serialize(),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46532. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46533. __decorate([
  46534. BABYLON.serialize(),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46536. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46537. __decorate([
  46538. BABYLON.serialize(),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46540. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46541. __decorate([
  46542. BABYLON.serialize(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46544. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46545. __decorate([
  46546. BABYLON.serialize(),
  46547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46548. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46549. __decorate([
  46550. BABYLON.serialize(),
  46551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46552. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46553. __decorate([
  46554. BABYLON.serialize(),
  46555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46556. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46557. __decorate([
  46558. BABYLON.serialize(),
  46559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46560. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46561. __decorate([
  46562. BABYLON.serialize(),
  46563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46564. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46565. __decorate([
  46566. BABYLON.serialize(),
  46567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46568. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46569. __decorate([
  46570. BABYLON.serialize(),
  46571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46572. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46573. __decorate([
  46574. BABYLON.serialize(),
  46575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46576. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46577. __decorate([
  46578. BABYLON.serialize(),
  46579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46580. ], PBRMaterial.prototype, "useParallax", void 0);
  46581. __decorate([
  46582. BABYLON.serialize(),
  46583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46584. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46585. __decorate([
  46586. BABYLON.serialize(),
  46587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46588. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46589. __decorate([
  46590. BABYLON.serialize(),
  46591. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46592. ], PBRMaterial.prototype, "disableLighting", void 0);
  46593. __decorate([
  46594. BABYLON.serialize(),
  46595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46596. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46597. __decorate([
  46598. BABYLON.serialize(),
  46599. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46600. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46601. __decorate([
  46602. BABYLON.serialize(),
  46603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46604. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46605. __decorate([
  46606. BABYLON.serialize(),
  46607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46608. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46609. __decorate([
  46610. BABYLON.serialize(),
  46611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46612. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46613. __decorate([
  46614. BABYLON.serialize(),
  46615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46616. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46617. __decorate([
  46618. BABYLON.serialize(),
  46619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46620. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46621. __decorate([
  46622. BABYLON.serializeAsTexture(),
  46623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46624. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46625. __decorate([
  46626. BABYLON.serialize(),
  46627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46628. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46629. __decorate([
  46630. BABYLON.serialize(),
  46631. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46632. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46633. __decorate([
  46634. BABYLON.serialize(),
  46635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46636. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46637. __decorate([
  46638. BABYLON.serialize(),
  46639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46640. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46641. __decorate([
  46642. BABYLON.serialize(),
  46643. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46644. ], PBRMaterial.prototype, "unlit", void 0);
  46645. return PBRMaterial;
  46646. }(BABYLON.PBRBaseMaterial));
  46647. BABYLON.PBRMaterial = PBRMaterial;
  46648. })(BABYLON || (BABYLON = {}));
  46649. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46650. var BABYLON;
  46651. (function (BABYLON) {
  46652. /**
  46653. * The PBR material of BJS following the metal roughness convention.
  46654. *
  46655. * This fits to the PBR convention in the GLTF definition:
  46656. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46657. */
  46658. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46659. __extends(PBRMetallicRoughnessMaterial, _super);
  46660. /**
  46661. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46662. *
  46663. * @param name The material name
  46664. * @param scene The scene the material will be use in.
  46665. */
  46666. function PBRMetallicRoughnessMaterial(name, scene) {
  46667. var _this = _super.call(this, name, scene) || this;
  46668. _this._useRoughnessFromMetallicTextureAlpha = false;
  46669. _this._useRoughnessFromMetallicTextureGreen = true;
  46670. _this._useMetallnessFromMetallicTextureBlue = true;
  46671. _this.metallic = 1.0;
  46672. _this.roughness = 1.0;
  46673. return _this;
  46674. }
  46675. /**
  46676. * Return the currrent class name of the material.
  46677. */
  46678. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46679. return "PBRMetallicRoughnessMaterial";
  46680. };
  46681. /**
  46682. * Return the active textures of the material.
  46683. */
  46684. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46685. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46686. if (this.baseTexture) {
  46687. activeTextures.push(this.baseTexture);
  46688. }
  46689. if (this.metallicRoughnessTexture) {
  46690. activeTextures.push(this.metallicRoughnessTexture);
  46691. }
  46692. return activeTextures;
  46693. };
  46694. /**
  46695. * Checks to see if a texture is used in the material.
  46696. * @param texture - Base texture to use.
  46697. * @returns - Boolean specifying if a texture is used in the material.
  46698. */
  46699. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46700. if (_super.prototype.hasTexture.call(this, texture)) {
  46701. return true;
  46702. }
  46703. if (this.baseTexture === texture) {
  46704. return true;
  46705. }
  46706. if (this.metallicRoughnessTexture === texture) {
  46707. return true;
  46708. }
  46709. return false;
  46710. };
  46711. /**
  46712. * Makes a duplicate of the current material.
  46713. * @param name - name to use for the new material.
  46714. */
  46715. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46716. var _this = this;
  46717. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46718. clone.id = name;
  46719. clone.name = name;
  46720. return clone;
  46721. };
  46722. /**
  46723. * Serialize the material to a parsable JSON object.
  46724. */
  46725. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46726. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46727. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46728. return serializationObject;
  46729. };
  46730. /**
  46731. * Parses a JSON object correponding to the serialize function.
  46732. */
  46733. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46734. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46735. };
  46736. __decorate([
  46737. BABYLON.serializeAsColor3(),
  46738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46739. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46740. __decorate([
  46741. BABYLON.serializeAsTexture(),
  46742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46743. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46744. __decorate([
  46745. BABYLON.serialize(),
  46746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46747. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46748. __decorate([
  46749. BABYLON.serialize(),
  46750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46751. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46752. __decorate([
  46753. BABYLON.serializeAsTexture(),
  46754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46755. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46756. return PBRMetallicRoughnessMaterial;
  46757. }(BABYLON.PBRBaseSimpleMaterial));
  46758. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46759. })(BABYLON || (BABYLON = {}));
  46760. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46761. var BABYLON;
  46762. (function (BABYLON) {
  46763. /**
  46764. * The PBR material of BJS following the specular glossiness convention.
  46765. *
  46766. * This fits to the PBR convention in the GLTF definition:
  46767. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46768. */
  46769. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46770. __extends(PBRSpecularGlossinessMaterial, _super);
  46771. /**
  46772. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46773. *
  46774. * @param name The material name
  46775. * @param scene The scene the material will be use in.
  46776. */
  46777. function PBRSpecularGlossinessMaterial(name, scene) {
  46778. var _this = _super.call(this, name, scene) || this;
  46779. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46780. return _this;
  46781. }
  46782. /**
  46783. * Return the currrent class name of the material.
  46784. */
  46785. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46786. return "PBRSpecularGlossinessMaterial";
  46787. };
  46788. /**
  46789. * Return the active textures of the material.
  46790. */
  46791. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46792. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46793. if (this.diffuseTexture) {
  46794. activeTextures.push(this.diffuseTexture);
  46795. }
  46796. if (this.specularGlossinessTexture) {
  46797. activeTextures.push(this.specularGlossinessTexture);
  46798. }
  46799. return activeTextures;
  46800. };
  46801. /**
  46802. * Checks to see if a texture is used in the material.
  46803. * @param texture - Base texture to use.
  46804. * @returns - Boolean specifying if a texture is used in the material.
  46805. */
  46806. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46807. if (_super.prototype.hasTexture.call(this, texture)) {
  46808. return true;
  46809. }
  46810. if (this.diffuseTexture === texture) {
  46811. return true;
  46812. }
  46813. if (this.specularGlossinessTexture === texture) {
  46814. return true;
  46815. }
  46816. return false;
  46817. };
  46818. /**
  46819. * Makes a duplicate of the current material.
  46820. * @param name - name to use for the new material.
  46821. */
  46822. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46823. var _this = this;
  46824. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46825. clone.id = name;
  46826. clone.name = name;
  46827. return clone;
  46828. };
  46829. /**
  46830. * Serialize the material to a parsable JSON object.
  46831. */
  46832. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46833. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46834. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46835. return serializationObject;
  46836. };
  46837. /**
  46838. * Parses a JSON object correponding to the serialize function.
  46839. */
  46840. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46841. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46842. };
  46843. __decorate([
  46844. BABYLON.serializeAsColor3("diffuse"),
  46845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46846. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46847. __decorate([
  46848. BABYLON.serializeAsTexture(),
  46849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46850. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46851. __decorate([
  46852. BABYLON.serializeAsColor3("specular"),
  46853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46854. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46855. __decorate([
  46856. BABYLON.serialize(),
  46857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46858. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46859. __decorate([
  46860. BABYLON.serializeAsTexture(),
  46861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46862. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46863. return PBRSpecularGlossinessMaterial;
  46864. }(BABYLON.PBRBaseSimpleMaterial));
  46865. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46866. })(BABYLON || (BABYLON = {}));
  46867. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46868. var BABYLON;
  46869. (function (BABYLON) {
  46870. BABYLON.CameraInputTypes = {};
  46871. var CameraInputsManager = /** @class */ (function () {
  46872. function CameraInputsManager(camera) {
  46873. this.attached = {};
  46874. this.camera = camera;
  46875. this.checkInputs = function () { };
  46876. }
  46877. /**
  46878. * Add an input method to a camera.
  46879. * builtin inputs example: camera.inputs.addGamepad();
  46880. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46881. * @param input camera input method
  46882. */
  46883. CameraInputsManager.prototype.add = function (input) {
  46884. var type = input.getSimpleName();
  46885. if (this.attached[type]) {
  46886. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46887. return;
  46888. }
  46889. this.attached[type] = input;
  46890. input.camera = this.camera;
  46891. //for checkInputs, we are dynamically creating a function
  46892. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46893. if (input.checkInputs) {
  46894. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46895. }
  46896. if (this.attachedElement) {
  46897. input.attachControl(this.attachedElement);
  46898. }
  46899. };
  46900. /**
  46901. * Remove a specific input method from a camera
  46902. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46903. * @param inputToRemove camera input method
  46904. */
  46905. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46906. for (var cam in this.attached) {
  46907. var input = this.attached[cam];
  46908. if (input === inputToRemove) {
  46909. input.detachControl(this.attachedElement);
  46910. input.camera = null;
  46911. delete this.attached[cam];
  46912. this.rebuildInputCheck();
  46913. }
  46914. }
  46915. };
  46916. CameraInputsManager.prototype.removeByType = function (inputType) {
  46917. for (var cam in this.attached) {
  46918. var input = this.attached[cam];
  46919. if (input.getClassName() === inputType) {
  46920. input.detachControl(this.attachedElement);
  46921. input.camera = null;
  46922. delete this.attached[cam];
  46923. this.rebuildInputCheck();
  46924. }
  46925. }
  46926. };
  46927. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46928. var current = this.checkInputs;
  46929. return function () {
  46930. current();
  46931. fn();
  46932. };
  46933. };
  46934. CameraInputsManager.prototype.attachInput = function (input) {
  46935. if (this.attachedElement) {
  46936. input.attachControl(this.attachedElement, this.noPreventDefault);
  46937. }
  46938. };
  46939. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46940. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46941. if (this.attachedElement) {
  46942. return;
  46943. }
  46944. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46945. this.attachedElement = element;
  46946. this.noPreventDefault = noPreventDefault;
  46947. for (var cam in this.attached) {
  46948. this.attached[cam].attachControl(element, noPreventDefault);
  46949. }
  46950. };
  46951. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46952. if (disconnect === void 0) { disconnect = false; }
  46953. if (this.attachedElement !== element) {
  46954. return;
  46955. }
  46956. for (var cam in this.attached) {
  46957. this.attached[cam].detachControl(element);
  46958. if (disconnect) {
  46959. this.attached[cam].camera = null;
  46960. }
  46961. }
  46962. this.attachedElement = null;
  46963. };
  46964. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46965. this.checkInputs = function () { };
  46966. for (var cam in this.attached) {
  46967. var input = this.attached[cam];
  46968. if (input.checkInputs) {
  46969. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46970. }
  46971. }
  46972. };
  46973. /**
  46974. * Remove all attached input methods from a camera
  46975. */
  46976. CameraInputsManager.prototype.clear = function () {
  46977. if (this.attachedElement) {
  46978. this.detachElement(this.attachedElement, true);
  46979. }
  46980. this.attached = {};
  46981. this.attachedElement = null;
  46982. this.checkInputs = function () { };
  46983. };
  46984. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46985. var inputs = {};
  46986. for (var cam in this.attached) {
  46987. var input = this.attached[cam];
  46988. var res = BABYLON.SerializationHelper.Serialize(input);
  46989. inputs[input.getClassName()] = res;
  46990. }
  46991. serializedCamera.inputsmgr = inputs;
  46992. };
  46993. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46994. var parsedInputs = parsedCamera.inputsmgr;
  46995. if (parsedInputs) {
  46996. this.clear();
  46997. for (var n in parsedInputs) {
  46998. var construct = BABYLON.CameraInputTypes[n];
  46999. if (construct) {
  47000. var parsedinput = parsedInputs[n];
  47001. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47002. this.add(input);
  47003. }
  47004. }
  47005. }
  47006. else {
  47007. //2016-03-08 this part is for managing backward compatibility
  47008. for (var n in this.attached) {
  47009. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47010. if (construct) {
  47011. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47012. this.remove(this.attached[n]);
  47013. this.add(input);
  47014. }
  47015. }
  47016. }
  47017. };
  47018. return CameraInputsManager;
  47019. }());
  47020. BABYLON.CameraInputsManager = CameraInputsManager;
  47021. })(BABYLON || (BABYLON = {}));
  47022. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47023. var BABYLON;
  47024. (function (BABYLON) {
  47025. var TargetCamera = /** @class */ (function (_super) {
  47026. __extends(TargetCamera, _super);
  47027. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47028. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47029. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47030. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47031. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47032. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47033. _this.speed = 2.0;
  47034. _this.noRotationConstraint = false;
  47035. _this.lockedTarget = null;
  47036. _this._currentTarget = BABYLON.Vector3.Zero();
  47037. _this._viewMatrix = BABYLON.Matrix.Zero();
  47038. _this._camMatrix = BABYLON.Matrix.Zero();
  47039. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47040. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47041. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47042. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47043. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47044. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47045. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47046. return _this;
  47047. }
  47048. TargetCamera.prototype.getFrontPosition = function (distance) {
  47049. this.getWorldMatrix();
  47050. var direction = this.getTarget().subtract(this.position);
  47051. direction.normalize();
  47052. direction.scaleInPlace(distance);
  47053. return this.globalPosition.add(direction);
  47054. };
  47055. TargetCamera.prototype._getLockedTargetPosition = function () {
  47056. if (!this.lockedTarget) {
  47057. return null;
  47058. }
  47059. if (this.lockedTarget.absolutePosition) {
  47060. this.lockedTarget.computeWorldMatrix();
  47061. }
  47062. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47063. };
  47064. TargetCamera.prototype.storeState = function () {
  47065. this._storedPosition = this.position.clone();
  47066. this._storedRotation = this.rotation.clone();
  47067. if (this.rotationQuaternion) {
  47068. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47069. }
  47070. return _super.prototype.storeState.call(this);
  47071. };
  47072. /**
  47073. * Restored camera state. You must call storeState() first
  47074. */
  47075. TargetCamera.prototype._restoreStateValues = function () {
  47076. if (!_super.prototype._restoreStateValues.call(this)) {
  47077. return false;
  47078. }
  47079. this.position = this._storedPosition.clone();
  47080. this.rotation = this._storedRotation.clone();
  47081. if (this.rotationQuaternion) {
  47082. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47083. }
  47084. this.cameraDirection.copyFromFloats(0, 0, 0);
  47085. this.cameraRotation.copyFromFloats(0, 0);
  47086. return true;
  47087. };
  47088. // Cache
  47089. TargetCamera.prototype._initCache = function () {
  47090. _super.prototype._initCache.call(this);
  47091. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47092. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47093. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47094. };
  47095. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47096. if (!ignoreParentClass) {
  47097. _super.prototype._updateCache.call(this);
  47098. }
  47099. var lockedTargetPosition = this._getLockedTargetPosition();
  47100. if (!lockedTargetPosition) {
  47101. this._cache.lockedTarget = null;
  47102. }
  47103. else {
  47104. if (!this._cache.lockedTarget) {
  47105. this._cache.lockedTarget = lockedTargetPosition.clone();
  47106. }
  47107. else {
  47108. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47109. }
  47110. }
  47111. this._cache.rotation.copyFrom(this.rotation);
  47112. if (this.rotationQuaternion)
  47113. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47114. };
  47115. // Synchronized
  47116. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47117. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47118. return false;
  47119. }
  47120. var lockedTargetPosition = this._getLockedTargetPosition();
  47121. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47122. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47123. };
  47124. // Methods
  47125. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47126. var engine = this.getEngine();
  47127. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47128. };
  47129. // Target
  47130. TargetCamera.prototype.setTarget = function (target) {
  47131. this.upVector.normalize();
  47132. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47133. this._camMatrix.invert();
  47134. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47135. var vDir = target.subtract(this.position);
  47136. if (vDir.x >= 0.0) {
  47137. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47138. }
  47139. else {
  47140. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47141. }
  47142. this.rotation.z = 0;
  47143. if (isNaN(this.rotation.x)) {
  47144. this.rotation.x = 0;
  47145. }
  47146. if (isNaN(this.rotation.y)) {
  47147. this.rotation.y = 0;
  47148. }
  47149. if (isNaN(this.rotation.z)) {
  47150. this.rotation.z = 0;
  47151. }
  47152. if (this.rotationQuaternion) {
  47153. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47154. }
  47155. };
  47156. /**
  47157. * Return the current target position of the camera. This value is expressed in local space.
  47158. */
  47159. TargetCamera.prototype.getTarget = function () {
  47160. return this._currentTarget;
  47161. };
  47162. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47163. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47164. };
  47165. TargetCamera.prototype._updatePosition = function () {
  47166. if (this.parent) {
  47167. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47168. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47169. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47170. return;
  47171. }
  47172. this.position.addInPlace(this.cameraDirection);
  47173. };
  47174. TargetCamera.prototype._checkInputs = function () {
  47175. var needToMove = this._decideIfNeedsToMove();
  47176. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47177. // Move
  47178. if (needToMove) {
  47179. this._updatePosition();
  47180. }
  47181. // Rotate
  47182. if (needToRotate) {
  47183. this.rotation.x += this.cameraRotation.x;
  47184. this.rotation.y += this.cameraRotation.y;
  47185. //rotate, if quaternion is set and rotation was used
  47186. if (this.rotationQuaternion) {
  47187. var len = this.rotation.lengthSquared();
  47188. if (len) {
  47189. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47190. }
  47191. }
  47192. if (!this.noRotationConstraint) {
  47193. var limit = (Math.PI / 2) * 0.95;
  47194. if (this.rotation.x > limit)
  47195. this.rotation.x = limit;
  47196. if (this.rotation.x < -limit)
  47197. this.rotation.x = -limit;
  47198. }
  47199. }
  47200. // Inertia
  47201. if (needToMove) {
  47202. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47203. this.cameraDirection.x = 0;
  47204. }
  47205. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47206. this.cameraDirection.y = 0;
  47207. }
  47208. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47209. this.cameraDirection.z = 0;
  47210. }
  47211. this.cameraDirection.scaleInPlace(this.inertia);
  47212. }
  47213. if (needToRotate) {
  47214. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47215. this.cameraRotation.x = 0;
  47216. }
  47217. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47218. this.cameraRotation.y = 0;
  47219. }
  47220. this.cameraRotation.scaleInPlace(this.inertia);
  47221. }
  47222. _super.prototype._checkInputs.call(this);
  47223. };
  47224. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47225. if (this.rotationQuaternion) {
  47226. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47227. }
  47228. else {
  47229. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47230. }
  47231. //update the up vector!
  47232. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47233. };
  47234. TargetCamera.prototype._getViewMatrix = function () {
  47235. if (this.lockedTarget) {
  47236. this.setTarget(this._getLockedTargetPosition());
  47237. }
  47238. // Compute
  47239. this._updateCameraRotationMatrix();
  47240. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47241. // Computing target and final matrix
  47242. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47243. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47244. return this._viewMatrix;
  47245. };
  47246. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47247. if (this.parent) {
  47248. var parentWorldMatrix = this.parent.getWorldMatrix();
  47249. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47250. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47251. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47252. this._markSyncedWithParent();
  47253. }
  47254. else {
  47255. this._globalPosition.copyFrom(this.position);
  47256. this._globalCurrentTarget.copyFrom(target);
  47257. this._globalCurrentUpVector.copyFrom(up);
  47258. }
  47259. if (this.getScene().useRightHandedSystem) {
  47260. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47261. }
  47262. else {
  47263. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47264. }
  47265. };
  47266. /**
  47267. * @override
  47268. * Override Camera.createRigCamera
  47269. */
  47270. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47271. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47272. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47273. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47274. if (!this.rotationQuaternion) {
  47275. this.rotationQuaternion = new BABYLON.Quaternion();
  47276. }
  47277. rigCamera._cameraRigParams = {};
  47278. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47279. }
  47280. return rigCamera;
  47281. }
  47282. return null;
  47283. };
  47284. /**
  47285. * @override
  47286. * Override Camera._updateRigCameras
  47287. */
  47288. TargetCamera.prototype._updateRigCameras = function () {
  47289. var camLeft = this._rigCameras[0];
  47290. var camRight = this._rigCameras[1];
  47291. switch (this.cameraRigMode) {
  47292. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47293. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47294. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47295. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47296. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47297. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47298. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47299. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47300. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47301. camLeft.setTarget(this.getTarget());
  47302. camRight.setTarget(this.getTarget());
  47303. break;
  47304. case BABYLON.Camera.RIG_MODE_VR:
  47305. if (camLeft.rotationQuaternion) {
  47306. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47307. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47308. }
  47309. else {
  47310. camLeft.rotation.copyFrom(this.rotation);
  47311. camRight.rotation.copyFrom(this.rotation);
  47312. }
  47313. camLeft.position.copyFrom(this.position);
  47314. camRight.position.copyFrom(this.position);
  47315. break;
  47316. }
  47317. _super.prototype._updateRigCameras.call(this);
  47318. };
  47319. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47320. if (!this._rigCamTransformMatrix) {
  47321. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47322. }
  47323. var target = this.getTarget();
  47324. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47325. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47326. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47327. };
  47328. TargetCamera.prototype.getClassName = function () {
  47329. return "TargetCamera";
  47330. };
  47331. __decorate([
  47332. BABYLON.serializeAsVector3()
  47333. ], TargetCamera.prototype, "rotation", void 0);
  47334. __decorate([
  47335. BABYLON.serialize()
  47336. ], TargetCamera.prototype, "speed", void 0);
  47337. __decorate([
  47338. BABYLON.serializeAsMeshReference("lockedTargetId")
  47339. ], TargetCamera.prototype, "lockedTarget", void 0);
  47340. return TargetCamera;
  47341. }(BABYLON.Camera));
  47342. BABYLON.TargetCamera = TargetCamera;
  47343. })(BABYLON || (BABYLON = {}));
  47344. //# sourceMappingURL=babylon.targetCamera.js.map
  47345. var BABYLON;
  47346. (function (BABYLON) {
  47347. var FreeCameraMouseInput = /** @class */ (function () {
  47348. function FreeCameraMouseInput(touchEnabled) {
  47349. if (touchEnabled === void 0) { touchEnabled = true; }
  47350. this.touchEnabled = touchEnabled;
  47351. this.buttons = [0, 1, 2];
  47352. this.angularSensibility = 2000.0;
  47353. this.previousPosition = null;
  47354. }
  47355. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47356. var _this = this;
  47357. var engine = this.camera.getEngine();
  47358. if (!this._pointerInput) {
  47359. this._pointerInput = function (p, s) {
  47360. var evt = p.event;
  47361. if (engine.isInVRExclusivePointerMode) {
  47362. return;
  47363. }
  47364. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47365. return;
  47366. }
  47367. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47368. return;
  47369. }
  47370. var srcElement = (evt.srcElement || evt.target);
  47371. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47372. try {
  47373. srcElement.setPointerCapture(evt.pointerId);
  47374. }
  47375. catch (e) {
  47376. //Nothing to do with the error. Execution will continue.
  47377. }
  47378. _this.previousPosition = {
  47379. x: evt.clientX,
  47380. y: evt.clientY
  47381. };
  47382. if (!noPreventDefault) {
  47383. evt.preventDefault();
  47384. element.focus();
  47385. }
  47386. }
  47387. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47388. try {
  47389. srcElement.releasePointerCapture(evt.pointerId);
  47390. }
  47391. catch (e) {
  47392. //Nothing to do with the error.
  47393. }
  47394. _this.previousPosition = null;
  47395. if (!noPreventDefault) {
  47396. evt.preventDefault();
  47397. }
  47398. }
  47399. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47400. if (!_this.previousPosition || engine.isPointerLock) {
  47401. return;
  47402. }
  47403. var offsetX = evt.clientX - _this.previousPosition.x;
  47404. if (_this.camera.getScene().useRightHandedSystem)
  47405. offsetX *= -1;
  47406. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47407. offsetX *= -1;
  47408. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47409. var offsetY = evt.clientY - _this.previousPosition.y;
  47410. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47411. _this.previousPosition = {
  47412. x: evt.clientX,
  47413. y: evt.clientY
  47414. };
  47415. if (!noPreventDefault) {
  47416. evt.preventDefault();
  47417. }
  47418. }
  47419. };
  47420. }
  47421. this._onMouseMove = function (evt) {
  47422. if (!engine.isPointerLock) {
  47423. return;
  47424. }
  47425. if (engine.isInVRExclusivePointerMode) {
  47426. return;
  47427. }
  47428. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47429. if (_this.camera.getScene().useRightHandedSystem)
  47430. offsetX *= -1;
  47431. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47432. offsetX *= -1;
  47433. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47434. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47435. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47436. _this.previousPosition = null;
  47437. if (!noPreventDefault) {
  47438. evt.preventDefault();
  47439. }
  47440. };
  47441. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47442. element.addEventListener("mousemove", this._onMouseMove, false);
  47443. };
  47444. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47445. if (this._observer && element) {
  47446. this.camera.getScene().onPointerObservable.remove(this._observer);
  47447. if (this._onMouseMove) {
  47448. element.removeEventListener("mousemove", this._onMouseMove);
  47449. }
  47450. this._observer = null;
  47451. this._onMouseMove = null;
  47452. this.previousPosition = null;
  47453. }
  47454. };
  47455. FreeCameraMouseInput.prototype.getClassName = function () {
  47456. return "FreeCameraMouseInput";
  47457. };
  47458. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47459. return "mouse";
  47460. };
  47461. __decorate([
  47462. BABYLON.serialize()
  47463. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47464. __decorate([
  47465. BABYLON.serialize()
  47466. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47467. return FreeCameraMouseInput;
  47468. }());
  47469. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47470. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47471. })(BABYLON || (BABYLON = {}));
  47472. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47473. var BABYLON;
  47474. (function (BABYLON) {
  47475. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47476. function FreeCameraKeyboardMoveInput() {
  47477. this._keys = new Array();
  47478. this.keysUp = [38];
  47479. this.keysDown = [40];
  47480. this.keysLeft = [37];
  47481. this.keysRight = [39];
  47482. }
  47483. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47484. var _this = this;
  47485. if (this._onCanvasBlurObserver) {
  47486. return;
  47487. }
  47488. this._scene = this.camera.getScene();
  47489. this._engine = this._scene.getEngine();
  47490. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47491. _this._keys = [];
  47492. });
  47493. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47494. var evt = info.event;
  47495. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47496. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47497. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47498. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47499. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47500. var index = _this._keys.indexOf(evt.keyCode);
  47501. if (index === -1) {
  47502. _this._keys.push(evt.keyCode);
  47503. }
  47504. if (!noPreventDefault) {
  47505. evt.preventDefault();
  47506. }
  47507. }
  47508. }
  47509. else {
  47510. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47511. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47512. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47513. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47514. var index = _this._keys.indexOf(evt.keyCode);
  47515. if (index >= 0) {
  47516. _this._keys.splice(index, 1);
  47517. }
  47518. if (!noPreventDefault) {
  47519. evt.preventDefault();
  47520. }
  47521. }
  47522. }
  47523. });
  47524. };
  47525. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47526. if (this._scene) {
  47527. if (this._onKeyboardObserver) {
  47528. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47529. }
  47530. if (this._onCanvasBlurObserver) {
  47531. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47532. }
  47533. this._onKeyboardObserver = null;
  47534. this._onCanvasBlurObserver = null;
  47535. }
  47536. this._keys = [];
  47537. };
  47538. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47539. if (this._onKeyboardObserver) {
  47540. var camera = this.camera;
  47541. // Keyboard
  47542. for (var index = 0; index < this._keys.length; index++) {
  47543. var keyCode = this._keys[index];
  47544. var speed = camera._computeLocalCameraSpeed();
  47545. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47546. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47547. }
  47548. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47549. camera._localDirection.copyFromFloats(0, 0, speed);
  47550. }
  47551. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47552. camera._localDirection.copyFromFloats(speed, 0, 0);
  47553. }
  47554. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47555. camera._localDirection.copyFromFloats(0, 0, -speed);
  47556. }
  47557. if (camera.getScene().useRightHandedSystem) {
  47558. camera._localDirection.z *= -1;
  47559. }
  47560. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47561. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47562. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47563. }
  47564. }
  47565. };
  47566. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47567. return "FreeCameraKeyboardMoveInput";
  47568. };
  47569. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47570. this._keys = [];
  47571. };
  47572. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47573. return "keyboard";
  47574. };
  47575. __decorate([
  47576. BABYLON.serialize()
  47577. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47578. __decorate([
  47579. BABYLON.serialize()
  47580. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47581. __decorate([
  47582. BABYLON.serialize()
  47583. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47584. __decorate([
  47585. BABYLON.serialize()
  47586. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47587. return FreeCameraKeyboardMoveInput;
  47588. }());
  47589. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47590. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47591. })(BABYLON || (BABYLON = {}));
  47592. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47593. var BABYLON;
  47594. (function (BABYLON) {
  47595. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47596. __extends(FreeCameraInputsManager, _super);
  47597. function FreeCameraInputsManager(camera) {
  47598. return _super.call(this, camera) || this;
  47599. }
  47600. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47601. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47602. return this;
  47603. };
  47604. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47605. if (touchEnabled === void 0) { touchEnabled = true; }
  47606. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47607. return this;
  47608. };
  47609. FreeCameraInputsManager.prototype.addGamepad = function () {
  47610. this.add(new BABYLON.FreeCameraGamepadInput());
  47611. return this;
  47612. };
  47613. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47614. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47615. return this;
  47616. };
  47617. FreeCameraInputsManager.prototype.addTouch = function () {
  47618. this.add(new BABYLON.FreeCameraTouchInput());
  47619. return this;
  47620. };
  47621. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47622. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47623. return this;
  47624. };
  47625. return FreeCameraInputsManager;
  47626. }(BABYLON.CameraInputsManager));
  47627. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47628. })(BABYLON || (BABYLON = {}));
  47629. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47630. var BABYLON;
  47631. (function (BABYLON) {
  47632. var FreeCamera = /** @class */ (function (_super) {
  47633. __extends(FreeCamera, _super);
  47634. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47635. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47636. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47637. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47638. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47639. _this.checkCollisions = false;
  47640. _this.applyGravity = false;
  47641. _this._needMoveForGravity = false;
  47642. _this._oldPosition = BABYLON.Vector3.Zero();
  47643. _this._diffPosition = BABYLON.Vector3.Zero();
  47644. _this._newPosition = BABYLON.Vector3.Zero();
  47645. // Collisions
  47646. _this._collisionMask = -1;
  47647. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47648. if (collidedMesh === void 0) { collidedMesh = null; }
  47649. //TODO move this to the collision coordinator!
  47650. if (_this.getScene().workerCollisions)
  47651. newPosition.multiplyInPlace(_this._collider._radius);
  47652. var updatePosition = function (newPos) {
  47653. _this._newPosition.copyFrom(newPos);
  47654. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47655. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47656. _this.position.addInPlace(_this._diffPosition);
  47657. if (_this.onCollide && collidedMesh) {
  47658. _this.onCollide(collidedMesh);
  47659. }
  47660. }
  47661. };
  47662. updatePosition(newPosition);
  47663. };
  47664. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47665. _this.inputs.addKeyboard().addMouse();
  47666. return _this;
  47667. }
  47668. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47669. //-- begin properties for backward compatibility for inputs
  47670. /**
  47671. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47672. * Higher values reduce sensitivity.
  47673. */
  47674. get: function () {
  47675. var mouse = this.inputs.attached["mouse"];
  47676. if (mouse)
  47677. return mouse.angularSensibility;
  47678. return 0;
  47679. },
  47680. /**
  47681. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47682. * Higher values reduce sensitivity.
  47683. */
  47684. set: function (value) {
  47685. var mouse = this.inputs.attached["mouse"];
  47686. if (mouse)
  47687. mouse.angularSensibility = value;
  47688. },
  47689. enumerable: true,
  47690. configurable: true
  47691. });
  47692. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47693. get: function () {
  47694. var keyboard = this.inputs.attached["keyboard"];
  47695. if (keyboard)
  47696. return keyboard.keysUp;
  47697. return [];
  47698. },
  47699. set: function (value) {
  47700. var keyboard = this.inputs.attached["keyboard"];
  47701. if (keyboard)
  47702. keyboard.keysUp = value;
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47708. get: function () {
  47709. var keyboard = this.inputs.attached["keyboard"];
  47710. if (keyboard)
  47711. return keyboard.keysDown;
  47712. return [];
  47713. },
  47714. set: function (value) {
  47715. var keyboard = this.inputs.attached["keyboard"];
  47716. if (keyboard)
  47717. keyboard.keysDown = value;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47723. get: function () {
  47724. var keyboard = this.inputs.attached["keyboard"];
  47725. if (keyboard)
  47726. return keyboard.keysLeft;
  47727. return [];
  47728. },
  47729. set: function (value) {
  47730. var keyboard = this.inputs.attached["keyboard"];
  47731. if (keyboard)
  47732. keyboard.keysLeft = value;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47738. get: function () {
  47739. var keyboard = this.inputs.attached["keyboard"];
  47740. if (keyboard)
  47741. return keyboard.keysRight;
  47742. return [];
  47743. },
  47744. set: function (value) {
  47745. var keyboard = this.inputs.attached["keyboard"];
  47746. if (keyboard)
  47747. keyboard.keysRight = value;
  47748. },
  47749. enumerable: true,
  47750. configurable: true
  47751. });
  47752. // Controls
  47753. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47754. this.inputs.attachElement(element, noPreventDefault);
  47755. };
  47756. FreeCamera.prototype.detachControl = function (element) {
  47757. this.inputs.detachElement(element);
  47758. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47759. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47760. };
  47761. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47762. get: function () {
  47763. return this._collisionMask;
  47764. },
  47765. set: function (mask) {
  47766. this._collisionMask = !isNaN(mask) ? mask : -1;
  47767. },
  47768. enumerable: true,
  47769. configurable: true
  47770. });
  47771. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47772. var globalPosition;
  47773. if (this.parent) {
  47774. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47775. }
  47776. else {
  47777. globalPosition = this.position;
  47778. }
  47779. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47780. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47781. if (!this._collider) {
  47782. this._collider = new BABYLON.Collider();
  47783. }
  47784. this._collider._radius = this.ellipsoid;
  47785. this._collider.collisionMask = this._collisionMask;
  47786. //no need for clone, as long as gravity is not on.
  47787. var actualDisplacement = displacement;
  47788. //add gravity to the direction to prevent the dual-collision checking
  47789. if (this.applyGravity) {
  47790. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47791. actualDisplacement = displacement.add(this.getScene().gravity);
  47792. }
  47793. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47794. };
  47795. FreeCamera.prototype._checkInputs = function () {
  47796. if (!this._localDirection) {
  47797. this._localDirection = BABYLON.Vector3.Zero();
  47798. this._transformedDirection = BABYLON.Vector3.Zero();
  47799. }
  47800. this.inputs.checkInputs();
  47801. _super.prototype._checkInputs.call(this);
  47802. };
  47803. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47804. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47805. };
  47806. FreeCamera.prototype._updatePosition = function () {
  47807. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47808. this._collideWithWorld(this.cameraDirection);
  47809. }
  47810. else {
  47811. _super.prototype._updatePosition.call(this);
  47812. }
  47813. };
  47814. FreeCamera.prototype.dispose = function () {
  47815. this.inputs.clear();
  47816. _super.prototype.dispose.call(this);
  47817. };
  47818. FreeCamera.prototype.getClassName = function () {
  47819. return "FreeCamera";
  47820. };
  47821. __decorate([
  47822. BABYLON.serializeAsVector3()
  47823. ], FreeCamera.prototype, "ellipsoid", void 0);
  47824. __decorate([
  47825. BABYLON.serializeAsVector3()
  47826. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47827. __decorate([
  47828. BABYLON.serialize()
  47829. ], FreeCamera.prototype, "checkCollisions", void 0);
  47830. __decorate([
  47831. BABYLON.serialize()
  47832. ], FreeCamera.prototype, "applyGravity", void 0);
  47833. return FreeCamera;
  47834. }(BABYLON.TargetCamera));
  47835. BABYLON.FreeCamera = FreeCamera;
  47836. })(BABYLON || (BABYLON = {}));
  47837. //# sourceMappingURL=babylon.freeCamera.js.map
  47838. var BABYLON;
  47839. (function (BABYLON) {
  47840. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47841. function ArcRotateCameraKeyboardMoveInput() {
  47842. this._keys = new Array();
  47843. this.keysUp = [38];
  47844. this.keysDown = [40];
  47845. this.keysLeft = [37];
  47846. this.keysRight = [39];
  47847. this.keysReset = [220];
  47848. this.panningSensibility = 50.0;
  47849. this.zoomingSensibility = 25.0;
  47850. this.useAltToZoom = true;
  47851. }
  47852. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47853. var _this = this;
  47854. if (this._onCanvasBlurObserver) {
  47855. return;
  47856. }
  47857. this._scene = this.camera.getScene();
  47858. this._engine = this._scene.getEngine();
  47859. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47860. _this._keys = [];
  47861. });
  47862. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47863. var evt = info.event;
  47864. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47865. _this._ctrlPressed = evt.ctrlKey;
  47866. _this._altPressed = evt.altKey;
  47867. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47868. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47869. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47870. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47871. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47872. var index = _this._keys.indexOf(evt.keyCode);
  47873. if (index === -1) {
  47874. _this._keys.push(evt.keyCode);
  47875. }
  47876. if (evt.preventDefault) {
  47877. if (!noPreventDefault) {
  47878. evt.preventDefault();
  47879. }
  47880. }
  47881. }
  47882. }
  47883. else {
  47884. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47885. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47886. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47887. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47888. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47889. var index = _this._keys.indexOf(evt.keyCode);
  47890. if (index >= 0) {
  47891. _this._keys.splice(index, 1);
  47892. }
  47893. if (evt.preventDefault) {
  47894. if (!noPreventDefault) {
  47895. evt.preventDefault();
  47896. }
  47897. }
  47898. }
  47899. }
  47900. });
  47901. };
  47902. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47903. if (this._scene) {
  47904. if (this._onKeyboardObserver) {
  47905. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47906. }
  47907. if (this._onCanvasBlurObserver) {
  47908. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47909. }
  47910. this._onKeyboardObserver = null;
  47911. this._onCanvasBlurObserver = null;
  47912. }
  47913. this._keys = [];
  47914. };
  47915. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47916. if (this._onKeyboardObserver) {
  47917. var camera = this.camera;
  47918. for (var index = 0; index < this._keys.length; index++) {
  47919. var keyCode = this._keys[index];
  47920. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47921. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47922. camera.inertialPanningX -= 1 / this.panningSensibility;
  47923. }
  47924. else {
  47925. camera.inertialAlphaOffset -= 0.01;
  47926. }
  47927. }
  47928. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47929. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47930. camera.inertialPanningY += 1 / this.panningSensibility;
  47931. }
  47932. else if (this._altPressed && this.useAltToZoom) {
  47933. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47934. }
  47935. else {
  47936. camera.inertialBetaOffset -= 0.01;
  47937. }
  47938. }
  47939. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47940. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47941. camera.inertialPanningX += 1 / this.panningSensibility;
  47942. }
  47943. else {
  47944. camera.inertialAlphaOffset += 0.01;
  47945. }
  47946. }
  47947. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47948. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47949. camera.inertialPanningY -= 1 / this.panningSensibility;
  47950. }
  47951. else if (this._altPressed && this.useAltToZoom) {
  47952. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47953. }
  47954. else {
  47955. camera.inertialBetaOffset += 0.01;
  47956. }
  47957. }
  47958. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47959. camera.restoreState();
  47960. }
  47961. }
  47962. }
  47963. };
  47964. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47965. return "ArcRotateCameraKeyboardMoveInput";
  47966. };
  47967. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47968. return "keyboard";
  47969. };
  47970. __decorate([
  47971. BABYLON.serialize()
  47972. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47973. __decorate([
  47974. BABYLON.serialize()
  47975. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47976. __decorate([
  47977. BABYLON.serialize()
  47978. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47979. __decorate([
  47980. BABYLON.serialize()
  47981. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47982. __decorate([
  47983. BABYLON.serialize()
  47984. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47985. __decorate([
  47986. BABYLON.serialize()
  47987. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47988. __decorate([
  47989. BABYLON.serialize()
  47990. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47991. __decorate([
  47992. BABYLON.serialize()
  47993. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47994. return ArcRotateCameraKeyboardMoveInput;
  47995. }());
  47996. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47997. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47998. })(BABYLON || (BABYLON = {}));
  47999. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48000. var BABYLON;
  48001. (function (BABYLON) {
  48002. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48003. function ArcRotateCameraMouseWheelInput() {
  48004. this.wheelPrecision = 3.0;
  48005. /**
  48006. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48007. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48008. */
  48009. this.wheelDeltaPercentage = 0;
  48010. }
  48011. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48012. var _this = this;
  48013. this._wheel = function (p, s) {
  48014. //sanity check - this should be a PointerWheel event.
  48015. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48016. return;
  48017. var event = p.event;
  48018. var delta = 0;
  48019. if (event.wheelDelta) {
  48020. if (_this.wheelDeltaPercentage) {
  48021. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48022. if (event.wheelDelta > 0) {
  48023. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48024. }
  48025. else {
  48026. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48027. }
  48028. }
  48029. else {
  48030. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48031. }
  48032. }
  48033. else if (event.detail) {
  48034. delta = -event.detail / _this.wheelPrecision;
  48035. }
  48036. if (delta)
  48037. _this.camera.inertialRadiusOffset += delta;
  48038. if (event.preventDefault) {
  48039. if (!noPreventDefault) {
  48040. event.preventDefault();
  48041. }
  48042. }
  48043. };
  48044. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48045. };
  48046. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48047. if (this._observer && element) {
  48048. this.camera.getScene().onPointerObservable.remove(this._observer);
  48049. this._observer = null;
  48050. this._wheel = null;
  48051. }
  48052. };
  48053. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48054. return "ArcRotateCameraMouseWheelInput";
  48055. };
  48056. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48057. return "mousewheel";
  48058. };
  48059. __decorate([
  48060. BABYLON.serialize()
  48061. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48062. __decorate([
  48063. BABYLON.serialize()
  48064. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48065. return ArcRotateCameraMouseWheelInput;
  48066. }());
  48067. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48068. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48069. })(BABYLON || (BABYLON = {}));
  48070. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48071. var BABYLON;
  48072. (function (BABYLON) {
  48073. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48074. function ArcRotateCameraPointersInput() {
  48075. this.buttons = [0, 1, 2];
  48076. this.angularSensibilityX = 1000.0;
  48077. this.angularSensibilityY = 1000.0;
  48078. this.pinchPrecision = 12.0;
  48079. /**
  48080. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48081. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48082. */
  48083. this.pinchDeltaPercentage = 0;
  48084. this.panningSensibility = 1000.0;
  48085. this.multiTouchPanning = true;
  48086. this.multiTouchPanAndZoom = true;
  48087. this._isPanClick = false;
  48088. this.pinchInwards = true;
  48089. }
  48090. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48091. var _this = this;
  48092. var engine = this.camera.getEngine();
  48093. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48094. var pointA = null;
  48095. var pointB = null;
  48096. var previousPinchSquaredDistance = 0;
  48097. var initialDistance = 0;
  48098. var twoFingerActivityCount = 0;
  48099. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48100. this._pointerInput = function (p, s) {
  48101. var evt = p.event;
  48102. var isTouch = p.event.pointerType === "touch";
  48103. if (engine.isInVRExclusivePointerMode) {
  48104. return;
  48105. }
  48106. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48107. return;
  48108. }
  48109. var srcElement = (evt.srcElement || evt.target);
  48110. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48111. try {
  48112. srcElement.setPointerCapture(evt.pointerId);
  48113. }
  48114. catch (e) {
  48115. //Nothing to do with the error. Execution will continue.
  48116. }
  48117. // Manage panning with pan button click
  48118. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48119. // manage pointers
  48120. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48121. if (pointA === null) {
  48122. pointA = cacheSoloPointer;
  48123. }
  48124. else if (pointB === null) {
  48125. pointB = cacheSoloPointer;
  48126. }
  48127. if (!noPreventDefault) {
  48128. evt.preventDefault();
  48129. element.focus();
  48130. }
  48131. }
  48132. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48133. _this.camera.restoreState();
  48134. }
  48135. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48136. try {
  48137. srcElement.releasePointerCapture(evt.pointerId);
  48138. }
  48139. catch (e) {
  48140. //Nothing to do with the error.
  48141. }
  48142. cacheSoloPointer = null;
  48143. previousPinchSquaredDistance = 0;
  48144. previousMultiTouchPanPosition.isPaning = false;
  48145. previousMultiTouchPanPosition.isPinching = false;
  48146. twoFingerActivityCount = 0;
  48147. initialDistance = 0;
  48148. if (!isTouch) {
  48149. pointB = null; // Mouse and pen are mono pointer
  48150. }
  48151. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48152. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48153. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48154. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48155. if (engine._badOS) {
  48156. pointA = pointB = null;
  48157. }
  48158. else {
  48159. //only remove the impacted pointer in case of multitouch allowing on most
  48160. //platforms switching from rotate to zoom and pan seamlessly.
  48161. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48162. pointA = pointB;
  48163. pointB = null;
  48164. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48165. }
  48166. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48167. pointB = null;
  48168. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48169. }
  48170. else {
  48171. pointA = pointB = null;
  48172. }
  48173. }
  48174. if (!noPreventDefault) {
  48175. evt.preventDefault();
  48176. }
  48177. }
  48178. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48179. if (!noPreventDefault) {
  48180. evt.preventDefault();
  48181. }
  48182. // One button down
  48183. if (pointA && pointB === null && cacheSoloPointer) {
  48184. if (_this.panningSensibility !== 0 &&
  48185. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48186. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48187. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48188. }
  48189. else {
  48190. var offsetX = evt.clientX - cacheSoloPointer.x;
  48191. var offsetY = evt.clientY - cacheSoloPointer.y;
  48192. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48193. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48194. }
  48195. cacheSoloPointer.x = evt.clientX;
  48196. cacheSoloPointer.y = evt.clientY;
  48197. }
  48198. // Two buttons down: pinch/pan
  48199. else if (pointA && pointB) {
  48200. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48201. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48202. ed.x = evt.clientX;
  48203. ed.y = evt.clientY;
  48204. var direction = _this.pinchInwards ? 1 : -1;
  48205. var distX = pointA.x - pointB.x;
  48206. var distY = pointA.y - pointB.y;
  48207. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48208. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48209. if (previousPinchSquaredDistance === 0) {
  48210. initialDistance = pinchDistance;
  48211. previousPinchSquaredDistance = pinchSquaredDistance;
  48212. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48213. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48214. return;
  48215. }
  48216. if (_this.multiTouchPanAndZoom) {
  48217. if (_this.pinchDeltaPercentage) {
  48218. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48219. }
  48220. else {
  48221. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48222. (_this.pinchPrecision *
  48223. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48224. direction);
  48225. }
  48226. if (_this.panningSensibility !== 0) {
  48227. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48228. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48229. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48230. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48231. previousMultiTouchPanPosition.x = pointersCenterX;
  48232. previousMultiTouchPanPosition.y = pointersCenterY;
  48233. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48234. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48235. }
  48236. }
  48237. else {
  48238. twoFingerActivityCount++;
  48239. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48240. if (_this.pinchDeltaPercentage) {
  48241. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48242. }
  48243. else {
  48244. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48245. (_this.pinchPrecision *
  48246. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48247. direction);
  48248. }
  48249. previousMultiTouchPanPosition.isPaning = false;
  48250. previousMultiTouchPanPosition.isPinching = true;
  48251. }
  48252. else {
  48253. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48254. if (!previousMultiTouchPanPosition.isPaning) {
  48255. previousMultiTouchPanPosition.isPaning = true;
  48256. previousMultiTouchPanPosition.isPinching = false;
  48257. previousMultiTouchPanPosition.x = ed.x;
  48258. previousMultiTouchPanPosition.y = ed.y;
  48259. return;
  48260. }
  48261. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48262. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48263. }
  48264. }
  48265. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48266. previousMultiTouchPanPosition.x = ed.x;
  48267. previousMultiTouchPanPosition.y = ed.y;
  48268. }
  48269. }
  48270. previousPinchSquaredDistance = pinchSquaredDistance;
  48271. }
  48272. }
  48273. };
  48274. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48275. this._onContextMenu = function (evt) {
  48276. evt.preventDefault();
  48277. };
  48278. if (!this.camera._useCtrlForPanning) {
  48279. element.addEventListener("contextmenu", this._onContextMenu, false);
  48280. }
  48281. this._onLostFocus = function () {
  48282. //this._keys = [];
  48283. pointA = pointB = null;
  48284. previousPinchSquaredDistance = 0;
  48285. previousMultiTouchPanPosition.isPaning = false;
  48286. previousMultiTouchPanPosition.isPinching = false;
  48287. twoFingerActivityCount = 0;
  48288. cacheSoloPointer = null;
  48289. initialDistance = 0;
  48290. };
  48291. this._onMouseMove = function (evt) {
  48292. if (!engine.isPointerLock) {
  48293. return;
  48294. }
  48295. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48296. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48297. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48298. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48299. if (!noPreventDefault) {
  48300. evt.preventDefault();
  48301. }
  48302. };
  48303. this._onGestureStart = function (e) {
  48304. if (window.MSGesture === undefined) {
  48305. return;
  48306. }
  48307. if (!_this._MSGestureHandler) {
  48308. _this._MSGestureHandler = new MSGesture();
  48309. _this._MSGestureHandler.target = element;
  48310. }
  48311. _this._MSGestureHandler.addPointer(e.pointerId);
  48312. };
  48313. this._onGesture = function (e) {
  48314. _this.camera.radius *= e.scale;
  48315. if (e.preventDefault) {
  48316. if (!noPreventDefault) {
  48317. e.stopPropagation();
  48318. e.preventDefault();
  48319. }
  48320. }
  48321. };
  48322. element.addEventListener("mousemove", this._onMouseMove, false);
  48323. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48324. element.addEventListener("MSGestureChange", this._onGesture, false);
  48325. BABYLON.Tools.RegisterTopRootEvents([
  48326. { name: "blur", handler: this._onLostFocus }
  48327. ]);
  48328. };
  48329. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48330. if (this._onLostFocus) {
  48331. BABYLON.Tools.UnregisterTopRootEvents([
  48332. { name: "blur", handler: this._onLostFocus }
  48333. ]);
  48334. }
  48335. if (element && this._observer) {
  48336. this.camera.getScene().onPointerObservable.remove(this._observer);
  48337. this._observer = null;
  48338. if (this._onContextMenu) {
  48339. element.removeEventListener("contextmenu", this._onContextMenu);
  48340. }
  48341. if (this._onMouseMove) {
  48342. element.removeEventListener("mousemove", this._onMouseMove);
  48343. }
  48344. if (this._onGestureStart) {
  48345. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48346. }
  48347. if (this._onGesture) {
  48348. element.removeEventListener("MSGestureChange", this._onGesture);
  48349. }
  48350. this._isPanClick = false;
  48351. this.pinchInwards = true;
  48352. this._onMouseMove = null;
  48353. this._onGestureStart = null;
  48354. this._onGesture = null;
  48355. this._MSGestureHandler = null;
  48356. this._onLostFocus = null;
  48357. this._onContextMenu = null;
  48358. }
  48359. };
  48360. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48361. return "ArcRotateCameraPointersInput";
  48362. };
  48363. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48364. return "pointers";
  48365. };
  48366. __decorate([
  48367. BABYLON.serialize()
  48368. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48369. __decorate([
  48370. BABYLON.serialize()
  48371. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48372. __decorate([
  48373. BABYLON.serialize()
  48374. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48375. __decorate([
  48376. BABYLON.serialize()
  48377. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48378. __decorate([
  48379. BABYLON.serialize()
  48380. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48381. __decorate([
  48382. BABYLON.serialize()
  48383. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48384. __decorate([
  48385. BABYLON.serialize()
  48386. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48387. __decorate([
  48388. BABYLON.serialize()
  48389. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48390. return ArcRotateCameraPointersInput;
  48391. }());
  48392. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48393. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48394. })(BABYLON || (BABYLON = {}));
  48395. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48396. var BABYLON;
  48397. (function (BABYLON) {
  48398. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48399. __extends(ArcRotateCameraInputsManager, _super);
  48400. function ArcRotateCameraInputsManager(camera) {
  48401. return _super.call(this, camera) || this;
  48402. }
  48403. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48404. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48405. return this;
  48406. };
  48407. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48408. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48409. return this;
  48410. };
  48411. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48412. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48413. return this;
  48414. };
  48415. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48416. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48417. return this;
  48418. };
  48419. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48420. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48421. return this;
  48422. };
  48423. return ArcRotateCameraInputsManager;
  48424. }(BABYLON.CameraInputsManager));
  48425. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48426. })(BABYLON || (BABYLON = {}));
  48427. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48428. var BABYLON;
  48429. (function (BABYLON) {
  48430. var ArcRotateCamera = /** @class */ (function (_super) {
  48431. __extends(ArcRotateCamera, _super);
  48432. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48433. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48434. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48435. _this.inertialAlphaOffset = 0;
  48436. _this.inertialBetaOffset = 0;
  48437. _this.inertialRadiusOffset = 0;
  48438. _this.lowerAlphaLimit = null;
  48439. _this.upperAlphaLimit = null;
  48440. _this.lowerBetaLimit = 0.01;
  48441. _this.upperBetaLimit = Math.PI;
  48442. _this.lowerRadiusLimit = null;
  48443. _this.upperRadiusLimit = null;
  48444. _this.inertialPanningX = 0;
  48445. _this.inertialPanningY = 0;
  48446. _this.pinchToPanMaxDistance = 20;
  48447. _this.panningDistanceLimit = null;
  48448. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48449. _this.panningInertia = 0.9;
  48450. //-- end properties for backward compatibility for inputs
  48451. _this.zoomOnFactor = 1;
  48452. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48453. _this.allowUpsideDown = true;
  48454. _this._viewMatrix = new BABYLON.Matrix();
  48455. // Panning
  48456. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48457. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48458. _this.checkCollisions = false;
  48459. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48460. _this._previousPosition = BABYLON.Vector3.Zero();
  48461. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48462. _this._newPosition = BABYLON.Vector3.Zero();
  48463. _this._computationVector = BABYLON.Vector3.Zero();
  48464. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48465. if (collidedMesh === void 0) { collidedMesh = null; }
  48466. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48467. newPosition.multiplyInPlace(_this._collider._radius);
  48468. }
  48469. if (!collidedMesh) {
  48470. _this._previousPosition.copyFrom(_this.position);
  48471. }
  48472. else {
  48473. _this.setPosition(newPosition);
  48474. if (_this.onCollide) {
  48475. _this.onCollide(collidedMesh);
  48476. }
  48477. }
  48478. // Recompute because of constraints
  48479. var cosa = Math.cos(_this.alpha);
  48480. var sina = Math.sin(_this.alpha);
  48481. var cosb = Math.cos(_this.beta);
  48482. var sinb = Math.sin(_this.beta);
  48483. if (sinb === 0) {
  48484. sinb = 0.0001;
  48485. }
  48486. var target = _this._getTargetPosition();
  48487. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48488. target.addToRef(_this._computationVector, _this._newPosition);
  48489. _this.position.copyFrom(_this._newPosition);
  48490. var up = _this.upVector;
  48491. if (_this.allowUpsideDown && _this.beta < 0) {
  48492. up = up.clone();
  48493. up = up.negate();
  48494. }
  48495. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48496. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48497. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48498. _this._collisionTriggered = false;
  48499. };
  48500. _this._target = BABYLON.Vector3.Zero();
  48501. if (target) {
  48502. _this.setTarget(target);
  48503. }
  48504. _this.alpha = alpha;
  48505. _this.beta = beta;
  48506. _this.radius = radius;
  48507. _this.getViewMatrix();
  48508. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48509. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48510. return _this;
  48511. }
  48512. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48513. get: function () {
  48514. return this._target;
  48515. },
  48516. set: function (value) {
  48517. this.setTarget(value);
  48518. },
  48519. enumerable: true,
  48520. configurable: true
  48521. });
  48522. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48523. //-- begin properties for backward compatibility for inputs
  48524. get: function () {
  48525. var pointers = this.inputs.attached["pointers"];
  48526. if (pointers)
  48527. return pointers.angularSensibilityX;
  48528. return 0;
  48529. },
  48530. set: function (value) {
  48531. var pointers = this.inputs.attached["pointers"];
  48532. if (pointers) {
  48533. pointers.angularSensibilityX = value;
  48534. }
  48535. },
  48536. enumerable: true,
  48537. configurable: true
  48538. });
  48539. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48540. get: function () {
  48541. var pointers = this.inputs.attached["pointers"];
  48542. if (pointers)
  48543. return pointers.angularSensibilityY;
  48544. return 0;
  48545. },
  48546. set: function (value) {
  48547. var pointers = this.inputs.attached["pointers"];
  48548. if (pointers) {
  48549. pointers.angularSensibilityY = value;
  48550. }
  48551. },
  48552. enumerable: true,
  48553. configurable: true
  48554. });
  48555. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48556. get: function () {
  48557. var pointers = this.inputs.attached["pointers"];
  48558. if (pointers)
  48559. return pointers.pinchPrecision;
  48560. return 0;
  48561. },
  48562. set: function (value) {
  48563. var pointers = this.inputs.attached["pointers"];
  48564. if (pointers) {
  48565. pointers.pinchPrecision = value;
  48566. }
  48567. },
  48568. enumerable: true,
  48569. configurable: true
  48570. });
  48571. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48572. get: function () {
  48573. var pointers = this.inputs.attached["pointers"];
  48574. if (pointers)
  48575. return pointers.pinchDeltaPercentage;
  48576. return 0;
  48577. },
  48578. set: function (value) {
  48579. var pointers = this.inputs.attached["pointers"];
  48580. if (pointers) {
  48581. pointers.pinchDeltaPercentage = value;
  48582. }
  48583. },
  48584. enumerable: true,
  48585. configurable: true
  48586. });
  48587. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48588. get: function () {
  48589. var pointers = this.inputs.attached["pointers"];
  48590. if (pointers)
  48591. return pointers.panningSensibility;
  48592. return 0;
  48593. },
  48594. set: function (value) {
  48595. var pointers = this.inputs.attached["pointers"];
  48596. if (pointers) {
  48597. pointers.panningSensibility = value;
  48598. }
  48599. },
  48600. enumerable: true,
  48601. configurable: true
  48602. });
  48603. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48604. get: function () {
  48605. var keyboard = this.inputs.attached["keyboard"];
  48606. if (keyboard)
  48607. return keyboard.keysUp;
  48608. return [];
  48609. },
  48610. set: function (value) {
  48611. var keyboard = this.inputs.attached["keyboard"];
  48612. if (keyboard)
  48613. keyboard.keysUp = value;
  48614. },
  48615. enumerable: true,
  48616. configurable: true
  48617. });
  48618. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48619. get: function () {
  48620. var keyboard = this.inputs.attached["keyboard"];
  48621. if (keyboard)
  48622. return keyboard.keysDown;
  48623. return [];
  48624. },
  48625. set: function (value) {
  48626. var keyboard = this.inputs.attached["keyboard"];
  48627. if (keyboard)
  48628. keyboard.keysDown = value;
  48629. },
  48630. enumerable: true,
  48631. configurable: true
  48632. });
  48633. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48634. get: function () {
  48635. var keyboard = this.inputs.attached["keyboard"];
  48636. if (keyboard)
  48637. return keyboard.keysLeft;
  48638. return [];
  48639. },
  48640. set: function (value) {
  48641. var keyboard = this.inputs.attached["keyboard"];
  48642. if (keyboard)
  48643. keyboard.keysLeft = value;
  48644. },
  48645. enumerable: true,
  48646. configurable: true
  48647. });
  48648. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48649. get: function () {
  48650. var keyboard = this.inputs.attached["keyboard"];
  48651. if (keyboard)
  48652. return keyboard.keysRight;
  48653. return [];
  48654. },
  48655. set: function (value) {
  48656. var keyboard = this.inputs.attached["keyboard"];
  48657. if (keyboard)
  48658. keyboard.keysRight = value;
  48659. },
  48660. enumerable: true,
  48661. configurable: true
  48662. });
  48663. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48664. get: function () {
  48665. var mousewheel = this.inputs.attached["mousewheel"];
  48666. if (mousewheel)
  48667. return mousewheel.wheelPrecision;
  48668. return 0;
  48669. },
  48670. set: function (value) {
  48671. var mousewheel = this.inputs.attached["mousewheel"];
  48672. if (mousewheel)
  48673. mousewheel.wheelPrecision = value;
  48674. },
  48675. enumerable: true,
  48676. configurable: true
  48677. });
  48678. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48679. get: function () {
  48680. var mousewheel = this.inputs.attached["mousewheel"];
  48681. if (mousewheel)
  48682. return mousewheel.wheelDeltaPercentage;
  48683. return 0;
  48684. },
  48685. set: function (value) {
  48686. var mousewheel = this.inputs.attached["mousewheel"];
  48687. if (mousewheel)
  48688. mousewheel.wheelDeltaPercentage = value;
  48689. },
  48690. enumerable: true,
  48691. configurable: true
  48692. });
  48693. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48694. get: function () {
  48695. return this._bouncingBehavior;
  48696. },
  48697. enumerable: true,
  48698. configurable: true
  48699. });
  48700. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48701. get: function () {
  48702. return this._bouncingBehavior != null;
  48703. },
  48704. set: function (value) {
  48705. if (value === this.useBouncingBehavior) {
  48706. return;
  48707. }
  48708. if (value) {
  48709. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48710. this.addBehavior(this._bouncingBehavior);
  48711. }
  48712. else if (this._bouncingBehavior) {
  48713. this.removeBehavior(this._bouncingBehavior);
  48714. this._bouncingBehavior = null;
  48715. }
  48716. },
  48717. enumerable: true,
  48718. configurable: true
  48719. });
  48720. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48721. get: function () {
  48722. return this._framingBehavior;
  48723. },
  48724. enumerable: true,
  48725. configurable: true
  48726. });
  48727. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48728. get: function () {
  48729. return this._framingBehavior != null;
  48730. },
  48731. set: function (value) {
  48732. if (value === this.useFramingBehavior) {
  48733. return;
  48734. }
  48735. if (value) {
  48736. this._framingBehavior = new BABYLON.FramingBehavior();
  48737. this.addBehavior(this._framingBehavior);
  48738. }
  48739. else if (this._framingBehavior) {
  48740. this.removeBehavior(this._framingBehavior);
  48741. this._framingBehavior = null;
  48742. }
  48743. },
  48744. enumerable: true,
  48745. configurable: true
  48746. });
  48747. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48748. get: function () {
  48749. return this._autoRotationBehavior;
  48750. },
  48751. enumerable: true,
  48752. configurable: true
  48753. });
  48754. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48755. get: function () {
  48756. return this._autoRotationBehavior != null;
  48757. },
  48758. set: function (value) {
  48759. if (value === this.useAutoRotationBehavior) {
  48760. return;
  48761. }
  48762. if (value) {
  48763. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48764. this.addBehavior(this._autoRotationBehavior);
  48765. }
  48766. else if (this._autoRotationBehavior) {
  48767. this.removeBehavior(this._autoRotationBehavior);
  48768. this._autoRotationBehavior = null;
  48769. }
  48770. },
  48771. enumerable: true,
  48772. configurable: true
  48773. });
  48774. // Cache
  48775. ArcRotateCamera.prototype._initCache = function () {
  48776. _super.prototype._initCache.call(this);
  48777. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48778. this._cache.alpha = undefined;
  48779. this._cache.beta = undefined;
  48780. this._cache.radius = undefined;
  48781. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48782. };
  48783. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48784. if (!ignoreParentClass) {
  48785. _super.prototype._updateCache.call(this);
  48786. }
  48787. this._cache._target.copyFrom(this._getTargetPosition());
  48788. this._cache.alpha = this.alpha;
  48789. this._cache.beta = this.beta;
  48790. this._cache.radius = this.radius;
  48791. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48792. };
  48793. ArcRotateCamera.prototype._getTargetPosition = function () {
  48794. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48795. var pos = this._targetHost.getAbsolutePosition();
  48796. if (this._targetBoundingCenter) {
  48797. pos.addToRef(this._targetBoundingCenter, this._target);
  48798. }
  48799. else {
  48800. this._target.copyFrom(pos);
  48801. }
  48802. }
  48803. var lockedTargetPosition = this._getLockedTargetPosition();
  48804. if (lockedTargetPosition) {
  48805. return lockedTargetPosition;
  48806. }
  48807. return this._target;
  48808. };
  48809. ArcRotateCamera.prototype.storeState = function () {
  48810. this._storedAlpha = this.alpha;
  48811. this._storedBeta = this.beta;
  48812. this._storedRadius = this.radius;
  48813. this._storedTarget = this._getTargetPosition().clone();
  48814. return _super.prototype.storeState.call(this);
  48815. };
  48816. /**
  48817. * Restored camera state. You must call storeState() first
  48818. */
  48819. ArcRotateCamera.prototype._restoreStateValues = function () {
  48820. if (!_super.prototype._restoreStateValues.call(this)) {
  48821. return false;
  48822. }
  48823. this.alpha = this._storedAlpha;
  48824. this.beta = this._storedBeta;
  48825. this.radius = this._storedRadius;
  48826. this.setTarget(this._storedTarget.clone());
  48827. this.inertialAlphaOffset = 0;
  48828. this.inertialBetaOffset = 0;
  48829. this.inertialRadiusOffset = 0;
  48830. this.inertialPanningX = 0;
  48831. this.inertialPanningY = 0;
  48832. return true;
  48833. };
  48834. // Synchronized
  48835. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48836. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48837. return false;
  48838. return this._cache._target.equals(this._getTargetPosition())
  48839. && this._cache.alpha === this.alpha
  48840. && this._cache.beta === this.beta
  48841. && this._cache.radius === this.radius
  48842. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48843. };
  48844. // Methods
  48845. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48846. var _this = this;
  48847. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48848. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48849. this._useCtrlForPanning = useCtrlForPanning;
  48850. this._panningMouseButton = panningMouseButton;
  48851. this.inputs.attachElement(element, noPreventDefault);
  48852. this._reset = function () {
  48853. _this.inertialAlphaOffset = 0;
  48854. _this.inertialBetaOffset = 0;
  48855. _this.inertialRadiusOffset = 0;
  48856. _this.inertialPanningX = 0;
  48857. _this.inertialPanningY = 0;
  48858. };
  48859. };
  48860. ArcRotateCamera.prototype.detachControl = function (element) {
  48861. this.inputs.detachElement(element);
  48862. if (this._reset) {
  48863. this._reset();
  48864. }
  48865. };
  48866. ArcRotateCamera.prototype._checkInputs = function () {
  48867. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48868. if (this._collisionTriggered) {
  48869. return;
  48870. }
  48871. this.inputs.checkInputs();
  48872. // Inertia
  48873. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48874. var inertialAlphaOffset = this.inertialAlphaOffset;
  48875. if (this.beta <= 0)
  48876. inertialAlphaOffset *= -1;
  48877. if (this.getScene().useRightHandedSystem)
  48878. inertialAlphaOffset *= -1;
  48879. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48880. inertialAlphaOffset *= -1;
  48881. this.alpha += inertialAlphaOffset;
  48882. this.beta += this.inertialBetaOffset;
  48883. this.radius -= this.inertialRadiusOffset;
  48884. this.inertialAlphaOffset *= this.inertia;
  48885. this.inertialBetaOffset *= this.inertia;
  48886. this.inertialRadiusOffset *= this.inertia;
  48887. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48888. this.inertialAlphaOffset = 0;
  48889. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48890. this.inertialBetaOffset = 0;
  48891. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48892. this.inertialRadiusOffset = 0;
  48893. }
  48894. // Panning inertia
  48895. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48896. if (!this._localDirection) {
  48897. this._localDirection = BABYLON.Vector3.Zero();
  48898. this._transformedDirection = BABYLON.Vector3.Zero();
  48899. }
  48900. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48901. this._localDirection.multiplyInPlace(this.panningAxis);
  48902. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48903. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48904. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48905. if (!this.panningAxis.y) {
  48906. this._transformedDirection.y = 0;
  48907. }
  48908. if (!this._targetHost) {
  48909. if (this.panningDistanceLimit) {
  48910. this._transformedDirection.addInPlace(this._target);
  48911. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48912. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48913. this._target.copyFrom(this._transformedDirection);
  48914. }
  48915. }
  48916. else {
  48917. this._target.addInPlace(this._transformedDirection);
  48918. }
  48919. }
  48920. this.inertialPanningX *= this.panningInertia;
  48921. this.inertialPanningY *= this.panningInertia;
  48922. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48923. this.inertialPanningX = 0;
  48924. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48925. this.inertialPanningY = 0;
  48926. }
  48927. // Limits
  48928. this._checkLimits();
  48929. _super.prototype._checkInputs.call(this);
  48930. };
  48931. ArcRotateCamera.prototype._checkLimits = function () {
  48932. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48933. if (this.allowUpsideDown && this.beta > Math.PI) {
  48934. this.beta = this.beta - (2 * Math.PI);
  48935. }
  48936. }
  48937. else {
  48938. if (this.beta < this.lowerBetaLimit) {
  48939. this.beta = this.lowerBetaLimit;
  48940. }
  48941. }
  48942. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48943. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48944. this.beta = this.beta + (2 * Math.PI);
  48945. }
  48946. }
  48947. else {
  48948. if (this.beta > this.upperBetaLimit) {
  48949. this.beta = this.upperBetaLimit;
  48950. }
  48951. }
  48952. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48953. this.alpha = this.lowerAlphaLimit;
  48954. }
  48955. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48956. this.alpha = this.upperAlphaLimit;
  48957. }
  48958. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48959. this.radius = this.lowerRadiusLimit;
  48960. }
  48961. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48962. this.radius = this.upperRadiusLimit;
  48963. }
  48964. };
  48965. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48966. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48967. this.radius = this._computationVector.length();
  48968. if (this.radius === 0) {
  48969. this.radius = 0.0001; // Just to avoid division by zero
  48970. }
  48971. // Alpha
  48972. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48973. if (this._computationVector.z < 0) {
  48974. this.alpha = 2 * Math.PI - this.alpha;
  48975. }
  48976. // Beta
  48977. this.beta = Math.acos(this._computationVector.y / this.radius);
  48978. this._checkLimits();
  48979. };
  48980. ArcRotateCamera.prototype.setPosition = function (position) {
  48981. if (this.position.equals(position)) {
  48982. return;
  48983. }
  48984. this.position.copyFrom(position);
  48985. this.rebuildAnglesAndRadius();
  48986. };
  48987. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48988. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48989. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48990. if (target.getBoundingInfo) {
  48991. if (toBoundingCenter) {
  48992. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48993. }
  48994. else {
  48995. this._targetBoundingCenter = null;
  48996. }
  48997. this._targetHost = target;
  48998. this._target = this._getTargetPosition();
  48999. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49000. }
  49001. else {
  49002. var newTarget = target;
  49003. var currentTarget = this._getTargetPosition();
  49004. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49005. return;
  49006. }
  49007. this._targetHost = null;
  49008. this._target = newTarget;
  49009. this._targetBoundingCenter = null;
  49010. this.onMeshTargetChangedObservable.notifyObservers(null);
  49011. }
  49012. this.rebuildAnglesAndRadius();
  49013. };
  49014. ArcRotateCamera.prototype._getViewMatrix = function () {
  49015. // Compute
  49016. var cosa = Math.cos(this.alpha);
  49017. var sina = Math.sin(this.alpha);
  49018. var cosb = Math.cos(this.beta);
  49019. var sinb = Math.sin(this.beta);
  49020. if (sinb === 0) {
  49021. sinb = 0.0001;
  49022. }
  49023. var target = this._getTargetPosition();
  49024. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49025. target.addToRef(this._computationVector, this._newPosition);
  49026. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49027. if (!this._collider) {
  49028. this._collider = new BABYLON.Collider();
  49029. }
  49030. this._collider._radius = this.collisionRadius;
  49031. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49032. this._collisionTriggered = true;
  49033. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49034. }
  49035. else {
  49036. this.position.copyFrom(this._newPosition);
  49037. var up = this.upVector;
  49038. if (this.allowUpsideDown && sinb < 0) {
  49039. up = up.clone();
  49040. up = up.negate();
  49041. }
  49042. this._computeViewMatrix(this.position, target, up);
  49043. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49044. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49045. }
  49046. this._currentTarget = target;
  49047. return this._viewMatrix;
  49048. };
  49049. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49050. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49051. meshes = meshes || this.getScene().meshes;
  49052. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49053. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49054. this.radius = distance * this.zoomOnFactor;
  49055. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49056. };
  49057. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49058. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49059. var meshesOrMinMaxVector;
  49060. var distance;
  49061. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49062. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49063. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49064. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49065. }
  49066. else { //minMaxVector and distance
  49067. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49068. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49069. distance = minMaxVectorAndDistance.distance;
  49070. }
  49071. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49072. if (!doNotUpdateMaxZ) {
  49073. this.maxZ = distance * 2;
  49074. }
  49075. };
  49076. /**
  49077. * @override
  49078. * Override Camera.createRigCamera
  49079. */
  49080. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49081. var alphaShift = 0;
  49082. switch (this.cameraRigMode) {
  49083. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49084. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49085. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49086. case BABYLON.Camera.RIG_MODE_VR:
  49087. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49088. break;
  49089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49090. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49091. break;
  49092. }
  49093. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49094. rigCam._cameraRigParams = {};
  49095. return rigCam;
  49096. };
  49097. /**
  49098. * @override
  49099. * Override Camera._updateRigCameras
  49100. */
  49101. ArcRotateCamera.prototype._updateRigCameras = function () {
  49102. var camLeft = this._rigCameras[0];
  49103. var camRight = this._rigCameras[1];
  49104. camLeft.beta = camRight.beta = this.beta;
  49105. camLeft.radius = camRight.radius = this.radius;
  49106. switch (this.cameraRigMode) {
  49107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49108. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49109. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49110. case BABYLON.Camera.RIG_MODE_VR:
  49111. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49112. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49113. break;
  49114. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49115. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49116. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49117. break;
  49118. }
  49119. _super.prototype._updateRigCameras.call(this);
  49120. };
  49121. ArcRotateCamera.prototype.dispose = function () {
  49122. this.inputs.clear();
  49123. _super.prototype.dispose.call(this);
  49124. };
  49125. ArcRotateCamera.prototype.getClassName = function () {
  49126. return "ArcRotateCamera";
  49127. };
  49128. __decorate([
  49129. BABYLON.serialize()
  49130. ], ArcRotateCamera.prototype, "alpha", void 0);
  49131. __decorate([
  49132. BABYLON.serialize()
  49133. ], ArcRotateCamera.prototype, "beta", void 0);
  49134. __decorate([
  49135. BABYLON.serialize()
  49136. ], ArcRotateCamera.prototype, "radius", void 0);
  49137. __decorate([
  49138. BABYLON.serializeAsVector3("target")
  49139. ], ArcRotateCamera.prototype, "_target", void 0);
  49140. __decorate([
  49141. BABYLON.serialize()
  49142. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49143. __decorate([
  49144. BABYLON.serialize()
  49145. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49146. __decorate([
  49147. BABYLON.serialize()
  49148. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49149. __decorate([
  49150. BABYLON.serialize()
  49151. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49152. __decorate([
  49153. BABYLON.serialize()
  49154. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49155. __decorate([
  49156. BABYLON.serialize()
  49157. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49158. __decorate([
  49159. BABYLON.serialize()
  49160. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49161. __decorate([
  49162. BABYLON.serialize()
  49163. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49164. __decorate([
  49165. BABYLON.serialize()
  49166. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49167. __decorate([
  49168. BABYLON.serialize()
  49169. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49170. __decorate([
  49171. BABYLON.serialize()
  49172. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49173. __decorate([
  49174. BABYLON.serialize()
  49175. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49176. __decorate([
  49177. BABYLON.serialize()
  49178. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49179. __decorate([
  49180. BABYLON.serializeAsVector3()
  49181. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49182. __decorate([
  49183. BABYLON.serialize()
  49184. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49185. __decorate([
  49186. BABYLON.serialize()
  49187. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49188. __decorate([
  49189. BABYLON.serialize()
  49190. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49191. return ArcRotateCamera;
  49192. }(BABYLON.TargetCamera));
  49193. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49194. })(BABYLON || (BABYLON = {}));
  49195. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49196. var BABYLON;
  49197. (function (BABYLON) {
  49198. /**
  49199. * The HemisphericLight simulates the ambient environment light,
  49200. * so the passed direction is the light reflection direction, not the incoming direction.
  49201. */
  49202. var HemisphericLight = /** @class */ (function (_super) {
  49203. __extends(HemisphericLight, _super);
  49204. /**
  49205. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49206. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49207. * The HemisphericLight can't cast shadows.
  49208. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49209. * @param name The friendly name of the light
  49210. * @param direction The direction of the light reflection
  49211. * @param scene The scene the light belongs to
  49212. */
  49213. function HemisphericLight(name, direction, scene) {
  49214. var _this = _super.call(this, name, scene) || this;
  49215. /**
  49216. * The groundColor is the light in the opposite direction to the one specified during creation.
  49217. * 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.
  49218. */
  49219. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49220. _this.direction = direction || BABYLON.Vector3.Up();
  49221. return _this;
  49222. }
  49223. HemisphericLight.prototype._buildUniformLayout = function () {
  49224. this._uniformBuffer.addUniform("vLightData", 4);
  49225. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49226. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49227. this._uniformBuffer.addUniform("vLightGround", 3);
  49228. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49229. this._uniformBuffer.addUniform("depthValues", 2);
  49230. this._uniformBuffer.create();
  49231. };
  49232. /**
  49233. * Returns the string "HemisphericLight".
  49234. * @return The class name
  49235. */
  49236. HemisphericLight.prototype.getClassName = function () {
  49237. return "HemisphericLight";
  49238. };
  49239. /**
  49240. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49241. * Returns the updated direction.
  49242. * @param target The target the direction should point to
  49243. * @return The computed direction
  49244. */
  49245. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49246. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49247. return this.direction;
  49248. };
  49249. /**
  49250. * Returns the shadow generator associated to the light.
  49251. * @returns Always null for hemispheric lights because it does not support shadows.
  49252. */
  49253. HemisphericLight.prototype.getShadowGenerator = function () {
  49254. return null;
  49255. };
  49256. /**
  49257. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49258. * @param effect The effect to update
  49259. * @param lightIndex The index of the light in the effect to update
  49260. * @returns The hemispheric light
  49261. */
  49262. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49263. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49264. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49265. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49266. return this;
  49267. };
  49268. /**
  49269. * @hidden internal use only.
  49270. */
  49271. HemisphericLight.prototype._getWorldMatrix = function () {
  49272. if (!this._worldMatrix) {
  49273. this._worldMatrix = BABYLON.Matrix.Identity();
  49274. }
  49275. return this._worldMatrix;
  49276. };
  49277. /**
  49278. * Returns the integer 3.
  49279. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49280. */
  49281. HemisphericLight.prototype.getTypeID = function () {
  49282. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49283. };
  49284. __decorate([
  49285. BABYLON.serializeAsColor3()
  49286. ], HemisphericLight.prototype, "groundColor", void 0);
  49287. __decorate([
  49288. BABYLON.serializeAsVector3()
  49289. ], HemisphericLight.prototype, "direction", void 0);
  49290. return HemisphericLight;
  49291. }(BABYLON.Light));
  49292. BABYLON.HemisphericLight = HemisphericLight;
  49293. })(BABYLON || (BABYLON = {}));
  49294. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49295. var BABYLON;
  49296. (function (BABYLON) {
  49297. /**
  49298. * Base implementation IShadowLight
  49299. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49300. */
  49301. var ShadowLight = /** @class */ (function (_super) {
  49302. __extends(ShadowLight, _super);
  49303. function ShadowLight() {
  49304. var _this = _super !== null && _super.apply(this, arguments) || this;
  49305. _this._needProjectionMatrixCompute = true;
  49306. return _this;
  49307. }
  49308. ShadowLight.prototype._setPosition = function (value) {
  49309. this._position = value;
  49310. };
  49311. Object.defineProperty(ShadowLight.prototype, "position", {
  49312. /**
  49313. * Sets the position the shadow will be casted from. Also use as the light position for both
  49314. * point and spot lights.
  49315. */
  49316. get: function () {
  49317. return this._position;
  49318. },
  49319. /**
  49320. * Sets the position the shadow will be casted from. Also use as the light position for both
  49321. * point and spot lights.
  49322. */
  49323. set: function (value) {
  49324. this._setPosition(value);
  49325. },
  49326. enumerable: true,
  49327. configurable: true
  49328. });
  49329. ShadowLight.prototype._setDirection = function (value) {
  49330. this._direction = value;
  49331. };
  49332. Object.defineProperty(ShadowLight.prototype, "direction", {
  49333. /**
  49334. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49335. * Also use as the light direction on spot and directional lights.
  49336. */
  49337. get: function () {
  49338. return this._direction;
  49339. },
  49340. /**
  49341. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49342. * Also use as the light direction on spot and directional lights.
  49343. */
  49344. set: function (value) {
  49345. this._setDirection(value);
  49346. },
  49347. enumerable: true,
  49348. configurable: true
  49349. });
  49350. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49351. /**
  49352. * Gets the shadow projection clipping minimum z value.
  49353. */
  49354. get: function () {
  49355. return this._shadowMinZ;
  49356. },
  49357. /**
  49358. * Sets the shadow projection clipping minimum z value.
  49359. */
  49360. set: function (value) {
  49361. this._shadowMinZ = value;
  49362. this.forceProjectionMatrixCompute();
  49363. },
  49364. enumerable: true,
  49365. configurable: true
  49366. });
  49367. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49368. /**
  49369. * Sets the shadow projection clipping maximum z value.
  49370. */
  49371. get: function () {
  49372. return this._shadowMaxZ;
  49373. },
  49374. /**
  49375. * Gets the shadow projection clipping maximum z value.
  49376. */
  49377. set: function (value) {
  49378. this._shadowMaxZ = value;
  49379. this.forceProjectionMatrixCompute();
  49380. },
  49381. enumerable: true,
  49382. configurable: true
  49383. });
  49384. /**
  49385. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49386. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49387. */
  49388. ShadowLight.prototype.computeTransformedInformation = function () {
  49389. if (this.parent && this.parent.getWorldMatrix) {
  49390. if (!this.transformedPosition) {
  49391. this.transformedPosition = BABYLON.Vector3.Zero();
  49392. }
  49393. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49394. // In case the direction is present.
  49395. if (this.direction) {
  49396. if (!this.transformedDirection) {
  49397. this.transformedDirection = BABYLON.Vector3.Zero();
  49398. }
  49399. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49400. }
  49401. return true;
  49402. }
  49403. return false;
  49404. };
  49405. /**
  49406. * Return the depth scale used for the shadow map.
  49407. * @returns the depth scale.
  49408. */
  49409. ShadowLight.prototype.getDepthScale = function () {
  49410. return 50.0;
  49411. };
  49412. /**
  49413. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49414. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49415. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49416. */
  49417. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49418. return this.transformedDirection ? this.transformedDirection : this.direction;
  49419. };
  49420. /**
  49421. * Returns the ShadowLight absolute position in the World.
  49422. * @returns the position vector in world space
  49423. */
  49424. ShadowLight.prototype.getAbsolutePosition = function () {
  49425. return this.transformedPosition ? this.transformedPosition : this.position;
  49426. };
  49427. /**
  49428. * Sets the ShadowLight direction toward the passed target.
  49429. * @param target The point tot target in local space
  49430. * @returns the updated ShadowLight direction
  49431. */
  49432. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49433. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49434. return this.direction;
  49435. };
  49436. /**
  49437. * Returns the light rotation in euler definition.
  49438. * @returns the x y z rotation in local space.
  49439. */
  49440. ShadowLight.prototype.getRotation = function () {
  49441. this.direction.normalize();
  49442. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49443. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49444. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49445. };
  49446. /**
  49447. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49448. * @returns true if a cube texture needs to be use
  49449. */
  49450. ShadowLight.prototype.needCube = function () {
  49451. return false;
  49452. };
  49453. /**
  49454. * Detects if the projection matrix requires to be recomputed this frame.
  49455. * @returns true if it requires to be recomputed otherwise, false.
  49456. */
  49457. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49458. return this._needProjectionMatrixCompute;
  49459. };
  49460. /**
  49461. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49462. */
  49463. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49464. this._needProjectionMatrixCompute = true;
  49465. };
  49466. /**
  49467. * Get the world matrix of the sahdow lights.
  49468. * @hidden Internal Use Only
  49469. */
  49470. ShadowLight.prototype._getWorldMatrix = function () {
  49471. if (!this._worldMatrix) {
  49472. this._worldMatrix = BABYLON.Matrix.Identity();
  49473. }
  49474. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49475. return this._worldMatrix;
  49476. };
  49477. /**
  49478. * Gets the minZ used for shadow according to both the scene and the light.
  49479. * @param activeCamera The camera we are returning the min for
  49480. * @returns the depth min z
  49481. */
  49482. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49483. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49484. };
  49485. /**
  49486. * Gets the maxZ used for shadow according to both the scene and the light.
  49487. * @param activeCamera The camera we are returning the max for
  49488. * @returns the depth max z
  49489. */
  49490. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49491. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49492. };
  49493. /**
  49494. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49495. * @param matrix The materix to updated with the projection information
  49496. * @param viewMatrix The transform matrix of the light
  49497. * @param renderList The list of mesh to render in the map
  49498. * @returns The current light
  49499. */
  49500. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49501. if (this.customProjectionMatrixBuilder) {
  49502. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49503. }
  49504. else {
  49505. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49506. }
  49507. return this;
  49508. };
  49509. __decorate([
  49510. BABYLON.serializeAsVector3()
  49511. ], ShadowLight.prototype, "position", null);
  49512. __decorate([
  49513. BABYLON.serializeAsVector3()
  49514. ], ShadowLight.prototype, "direction", null);
  49515. __decorate([
  49516. BABYLON.serialize()
  49517. ], ShadowLight.prototype, "shadowMinZ", null);
  49518. __decorate([
  49519. BABYLON.serialize()
  49520. ], ShadowLight.prototype, "shadowMaxZ", null);
  49521. return ShadowLight;
  49522. }(BABYLON.Light));
  49523. BABYLON.ShadowLight = ShadowLight;
  49524. })(BABYLON || (BABYLON = {}));
  49525. //# sourceMappingURL=babylon.shadowLight.js.map
  49526. var BABYLON;
  49527. (function (BABYLON) {
  49528. /**
  49529. * A point light is a light defined by an unique point in world space.
  49530. * The light is emitted in every direction from this point.
  49531. * A good example of a point light is a standard light bulb.
  49532. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49533. */
  49534. var PointLight = /** @class */ (function (_super) {
  49535. __extends(PointLight, _super);
  49536. /**
  49537. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49538. * A PointLight emits the light in every direction.
  49539. * It can cast shadows.
  49540. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49541. * ```javascript
  49542. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49543. * ```
  49544. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49545. * @param name The light friendly name
  49546. * @param position The position of the point light in the scene
  49547. * @param scene The scene the lights belongs to
  49548. */
  49549. function PointLight(name, position, scene) {
  49550. var _this = _super.call(this, name, scene) || this;
  49551. _this._shadowAngle = Math.PI / 2;
  49552. _this.position = position;
  49553. return _this;
  49554. }
  49555. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49556. /**
  49557. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49558. * This specifies what angle the shadow will use to be created.
  49559. *
  49560. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49561. */
  49562. get: function () {
  49563. return this._shadowAngle;
  49564. },
  49565. /**
  49566. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49567. * This specifies what angle the shadow will use to be created.
  49568. *
  49569. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49570. */
  49571. set: function (value) {
  49572. this._shadowAngle = value;
  49573. this.forceProjectionMatrixCompute();
  49574. },
  49575. enumerable: true,
  49576. configurable: true
  49577. });
  49578. Object.defineProperty(PointLight.prototype, "direction", {
  49579. /**
  49580. * Gets the direction if it has been set.
  49581. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49582. */
  49583. get: function () {
  49584. return this._direction;
  49585. },
  49586. /**
  49587. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49588. */
  49589. set: function (value) {
  49590. var previousNeedCube = this.needCube();
  49591. this._direction = value;
  49592. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49593. this._shadowGenerator.recreateShadowMap();
  49594. }
  49595. },
  49596. enumerable: true,
  49597. configurable: true
  49598. });
  49599. /**
  49600. * Returns the string "PointLight"
  49601. * @returns the class name
  49602. */
  49603. PointLight.prototype.getClassName = function () {
  49604. return "PointLight";
  49605. };
  49606. /**
  49607. * Returns the integer 0.
  49608. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49609. */
  49610. PointLight.prototype.getTypeID = function () {
  49611. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49612. };
  49613. /**
  49614. * Specifies wether or not the shadowmap should be a cube texture.
  49615. * @returns true if the shadowmap needs to be a cube texture.
  49616. */
  49617. PointLight.prototype.needCube = function () {
  49618. return !this.direction;
  49619. };
  49620. /**
  49621. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49622. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49623. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49624. */
  49625. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49626. if (this.direction) {
  49627. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49628. }
  49629. else {
  49630. switch (faceIndex) {
  49631. case 0:
  49632. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49633. case 1:
  49634. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49635. case 2:
  49636. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49637. case 3:
  49638. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49639. case 4:
  49640. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49641. case 5:
  49642. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49643. }
  49644. }
  49645. return BABYLON.Vector3.Zero();
  49646. };
  49647. /**
  49648. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49649. * - fov = PI / 2
  49650. * - aspect ratio : 1.0
  49651. * - z-near and far equal to the active camera minZ and maxZ.
  49652. * Returns the PointLight.
  49653. */
  49654. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49655. var activeCamera = this.getScene().activeCamera;
  49656. if (!activeCamera) {
  49657. return;
  49658. }
  49659. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49660. };
  49661. PointLight.prototype._buildUniformLayout = function () {
  49662. this._uniformBuffer.addUniform("vLightData", 4);
  49663. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49664. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49665. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49666. this._uniformBuffer.addUniform("depthValues", 2);
  49667. this._uniformBuffer.create();
  49668. };
  49669. /**
  49670. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49671. * @param effect The effect to update
  49672. * @param lightIndex The index of the light in the effect to update
  49673. * @returns The point light
  49674. */
  49675. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49676. if (this.computeTransformedInformation()) {
  49677. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49678. return this;
  49679. }
  49680. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49681. return this;
  49682. };
  49683. __decorate([
  49684. BABYLON.serialize()
  49685. ], PointLight.prototype, "shadowAngle", null);
  49686. return PointLight;
  49687. }(BABYLON.ShadowLight));
  49688. BABYLON.PointLight = PointLight;
  49689. })(BABYLON || (BABYLON = {}));
  49690. //# sourceMappingURL=babylon.pointLight.js.map
  49691. var BABYLON;
  49692. (function (BABYLON) {
  49693. /**
  49694. * A directional light is defined by a direction (what a surprise!).
  49695. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49696. * 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.
  49697. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49698. */
  49699. var DirectionalLight = /** @class */ (function (_super) {
  49700. __extends(DirectionalLight, _super);
  49701. /**
  49702. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49703. * The directional light is emitted from everywhere in the given direction.
  49704. * It can cast shawdows.
  49705. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49706. * @param name The friendly name of the light
  49707. * @param direction The direction of the light
  49708. * @param scene The scene the light belongs to
  49709. */
  49710. function DirectionalLight(name, direction, scene) {
  49711. var _this = _super.call(this, name, scene) || this;
  49712. _this._shadowFrustumSize = 0;
  49713. _this._shadowOrthoScale = 0.1;
  49714. /**
  49715. * Automatically compute the projection matrix to best fit (including all the casters)
  49716. * on each frame.
  49717. */
  49718. _this.autoUpdateExtends = true;
  49719. // Cache
  49720. _this._orthoLeft = Number.MAX_VALUE;
  49721. _this._orthoRight = Number.MIN_VALUE;
  49722. _this._orthoTop = Number.MIN_VALUE;
  49723. _this._orthoBottom = Number.MAX_VALUE;
  49724. _this.position = direction.scale(-1.0);
  49725. _this.direction = direction;
  49726. return _this;
  49727. }
  49728. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49729. /**
  49730. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49731. */
  49732. get: function () {
  49733. return this._shadowFrustumSize;
  49734. },
  49735. /**
  49736. * Specifies a fix frustum size for the shadow generation.
  49737. */
  49738. set: function (value) {
  49739. this._shadowFrustumSize = value;
  49740. this.forceProjectionMatrixCompute();
  49741. },
  49742. enumerable: true,
  49743. configurable: true
  49744. });
  49745. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49746. /**
  49747. * Gets the shadow projection scale against the optimal computed one.
  49748. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49749. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49750. */
  49751. get: function () {
  49752. return this._shadowOrthoScale;
  49753. },
  49754. /**
  49755. * Sets the shadow projection scale against the optimal computed one.
  49756. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49757. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49758. */
  49759. set: function (value) {
  49760. this._shadowOrthoScale = value;
  49761. this.forceProjectionMatrixCompute();
  49762. },
  49763. enumerable: true,
  49764. configurable: true
  49765. });
  49766. /**
  49767. * Returns the string "DirectionalLight".
  49768. * @return The class name
  49769. */
  49770. DirectionalLight.prototype.getClassName = function () {
  49771. return "DirectionalLight";
  49772. };
  49773. /**
  49774. * Returns the integer 1.
  49775. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49776. */
  49777. DirectionalLight.prototype.getTypeID = function () {
  49778. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49779. };
  49780. /**
  49781. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49782. * Returns the DirectionalLight Shadow projection matrix.
  49783. */
  49784. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49785. if (this.shadowFrustumSize > 0) {
  49786. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49787. }
  49788. else {
  49789. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49790. }
  49791. };
  49792. /**
  49793. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49794. * Returns the DirectionalLight Shadow projection matrix.
  49795. */
  49796. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49797. var activeCamera = this.getScene().activeCamera;
  49798. if (!activeCamera) {
  49799. return;
  49800. }
  49801. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49802. };
  49803. /**
  49804. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49805. * Returns the DirectionalLight Shadow projection matrix.
  49806. */
  49807. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49808. var activeCamera = this.getScene().activeCamera;
  49809. if (!activeCamera) {
  49810. return;
  49811. }
  49812. // Check extends
  49813. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49814. var tempVector3 = BABYLON.Vector3.Zero();
  49815. this._orthoLeft = Number.MAX_VALUE;
  49816. this._orthoRight = Number.MIN_VALUE;
  49817. this._orthoTop = Number.MIN_VALUE;
  49818. this._orthoBottom = Number.MAX_VALUE;
  49819. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49820. var mesh = renderList[meshIndex];
  49821. if (!mesh) {
  49822. continue;
  49823. }
  49824. var boundingInfo = mesh.getBoundingInfo();
  49825. var boundingBox = boundingInfo.boundingBox;
  49826. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49827. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49828. if (tempVector3.x < this._orthoLeft)
  49829. this._orthoLeft = tempVector3.x;
  49830. if (tempVector3.y < this._orthoBottom)
  49831. this._orthoBottom = tempVector3.y;
  49832. if (tempVector3.x > this._orthoRight)
  49833. this._orthoRight = tempVector3.x;
  49834. if (tempVector3.y > this._orthoTop)
  49835. this._orthoTop = tempVector3.y;
  49836. }
  49837. }
  49838. }
  49839. var xOffset = this._orthoRight - this._orthoLeft;
  49840. var yOffset = this._orthoTop - this._orthoBottom;
  49841. 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);
  49842. };
  49843. DirectionalLight.prototype._buildUniformLayout = function () {
  49844. this._uniformBuffer.addUniform("vLightData", 4);
  49845. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49846. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49847. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49848. this._uniformBuffer.addUniform("depthValues", 2);
  49849. this._uniformBuffer.create();
  49850. };
  49851. /**
  49852. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49853. * @param effect The effect to update
  49854. * @param lightIndex The index of the light in the effect to update
  49855. * @returns The directional light
  49856. */
  49857. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49858. if (this.computeTransformedInformation()) {
  49859. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49860. return this;
  49861. }
  49862. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49863. return this;
  49864. };
  49865. /**
  49866. * Gets the minZ used for shadow according to both the scene and the light.
  49867. *
  49868. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49869. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49870. * @param activeCamera The camera we are returning the min for
  49871. * @returns the depth min z
  49872. */
  49873. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49874. return 1;
  49875. };
  49876. /**
  49877. * Gets the maxZ used for shadow according to both the scene and the light.
  49878. *
  49879. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49880. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49881. * @param activeCamera The camera we are returning the max for
  49882. * @returns the depth max z
  49883. */
  49884. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49885. return 1;
  49886. };
  49887. __decorate([
  49888. BABYLON.serialize()
  49889. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49890. __decorate([
  49891. BABYLON.serialize()
  49892. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49893. __decorate([
  49894. BABYLON.serialize()
  49895. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49896. return DirectionalLight;
  49897. }(BABYLON.ShadowLight));
  49898. BABYLON.DirectionalLight = DirectionalLight;
  49899. })(BABYLON || (BABYLON = {}));
  49900. //# sourceMappingURL=babylon.directionalLight.js.map
  49901. var BABYLON;
  49902. (function (BABYLON) {
  49903. /**
  49904. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49905. * These values define a cone of light starting from the position, emitting toward the direction.
  49906. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49907. * and the exponent defines the speed of the decay of the light with distance (reach).
  49908. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49909. */
  49910. var SpotLight = /** @class */ (function (_super) {
  49911. __extends(SpotLight, _super);
  49912. /**
  49913. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49914. * It can cast shadows.
  49915. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49916. * @param name The light friendly name
  49917. * @param position The position of the spot light in the scene
  49918. * @param direction The direction of the light in the scene
  49919. * @param angle The cone angle of the light in Radians
  49920. * @param exponent The light decay speed with the distance from the emission spot
  49921. * @param scene The scene the lights belongs to
  49922. */
  49923. function SpotLight(name, position, direction, angle, exponent, scene) {
  49924. var _this = _super.call(this, name, scene) || this;
  49925. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49926. _this._projectionTextureLightNear = 1e-6;
  49927. _this._projectionTextureLightFar = 1000.0;
  49928. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49929. _this._projectionTextureViewLightDirty = true;
  49930. _this._projectionTextureProjectionLightDirty = true;
  49931. _this._projectionTextureDirty = true;
  49932. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49933. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49934. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49935. _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);
  49936. _this.position = position;
  49937. _this.direction = direction;
  49938. _this.angle = angle;
  49939. _this.exponent = exponent;
  49940. return _this;
  49941. }
  49942. Object.defineProperty(SpotLight.prototype, "angle", {
  49943. /**
  49944. * Gets the cone angle of the spot light in Radians.
  49945. */
  49946. get: function () {
  49947. return this._angle;
  49948. },
  49949. /**
  49950. * Sets the cone angle of the spot light in Radians.
  49951. */
  49952. set: function (value) {
  49953. this._angle = value;
  49954. this._projectionTextureProjectionLightDirty = true;
  49955. this.forceProjectionMatrixCompute();
  49956. },
  49957. enumerable: true,
  49958. configurable: true
  49959. });
  49960. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49961. /**
  49962. * Allows scaling the angle of the light for shadow generation only.
  49963. */
  49964. get: function () {
  49965. return this._shadowAngleScale;
  49966. },
  49967. /**
  49968. * Allows scaling the angle of the light for shadow generation only.
  49969. */
  49970. set: function (value) {
  49971. this._shadowAngleScale = value;
  49972. this.forceProjectionMatrixCompute();
  49973. },
  49974. enumerable: true,
  49975. configurable: true
  49976. });
  49977. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49978. /**
  49979. * Allows reading the projecton texture
  49980. */
  49981. get: function () {
  49982. return this._projectionTextureMatrix;
  49983. },
  49984. enumerable: true,
  49985. configurable: true
  49986. });
  49987. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49988. /**
  49989. * Gets the near clip of the Spotlight for texture projection.
  49990. */
  49991. get: function () {
  49992. return this._projectionTextureLightNear;
  49993. },
  49994. /**
  49995. * Sets the near clip of the Spotlight for texture projection.
  49996. */
  49997. set: function (value) {
  49998. this._projectionTextureLightNear = value;
  49999. this._projectionTextureProjectionLightDirty = true;
  50000. },
  50001. enumerable: true,
  50002. configurable: true
  50003. });
  50004. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50005. /**
  50006. * Gets the far clip of the Spotlight for texture projection.
  50007. */
  50008. get: function () {
  50009. return this._projectionTextureLightFar;
  50010. },
  50011. /**
  50012. * Sets the far clip of the Spotlight for texture projection.
  50013. */
  50014. set: function (value) {
  50015. this._projectionTextureLightFar = value;
  50016. this._projectionTextureProjectionLightDirty = true;
  50017. },
  50018. enumerable: true,
  50019. configurable: true
  50020. });
  50021. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50022. /**
  50023. * Gets the Up vector of the Spotlight for texture projection.
  50024. */
  50025. get: function () {
  50026. return this._projectionTextureUpDirection;
  50027. },
  50028. /**
  50029. * Sets the Up vector of the Spotlight for texture projection.
  50030. */
  50031. set: function (value) {
  50032. this._projectionTextureUpDirection = value;
  50033. this._projectionTextureProjectionLightDirty = true;
  50034. },
  50035. enumerable: true,
  50036. configurable: true
  50037. });
  50038. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50039. /**
  50040. * Gets the projection texture of the light.
  50041. */
  50042. get: function () {
  50043. return this._projectionTexture;
  50044. },
  50045. /**
  50046. * Sets the projection texture of the light.
  50047. */
  50048. set: function (value) {
  50049. this._projectionTexture = value;
  50050. this._projectionTextureDirty = true;
  50051. },
  50052. enumerable: true,
  50053. configurable: true
  50054. });
  50055. /**
  50056. * Returns the string "SpotLight".
  50057. * @returns the class name
  50058. */
  50059. SpotLight.prototype.getClassName = function () {
  50060. return "SpotLight";
  50061. };
  50062. /**
  50063. * Returns the integer 2.
  50064. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50065. */
  50066. SpotLight.prototype.getTypeID = function () {
  50067. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50068. };
  50069. /**
  50070. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50071. */
  50072. SpotLight.prototype._setDirection = function (value) {
  50073. _super.prototype._setDirection.call(this, value);
  50074. this._projectionTextureViewLightDirty = true;
  50075. };
  50076. /**
  50077. * Overrides the position setter to recompute the projection texture view light Matrix.
  50078. */
  50079. SpotLight.prototype._setPosition = function (value) {
  50080. _super.prototype._setPosition.call(this, value);
  50081. this._projectionTextureViewLightDirty = true;
  50082. };
  50083. /**
  50084. * 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.
  50085. * Returns the SpotLight.
  50086. */
  50087. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50088. var activeCamera = this.getScene().activeCamera;
  50089. if (!activeCamera) {
  50090. return;
  50091. }
  50092. this._shadowAngleScale = this._shadowAngleScale || 1;
  50093. var angle = this._shadowAngleScale * this._angle;
  50094. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50095. };
  50096. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50097. this._projectionTextureViewLightDirty = false;
  50098. this._projectionTextureDirty = true;
  50099. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50100. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50101. };
  50102. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50103. this._projectionTextureProjectionLightDirty = false;
  50104. this._projectionTextureDirty = true;
  50105. var light_far = this.projectionTextureLightFar;
  50106. var light_near = this.projectionTextureLightNear;
  50107. var P = light_far / (light_far - light_near);
  50108. var Q = -P * light_near;
  50109. var S = 1.0 / Math.tan(this._angle / 2.0);
  50110. var A = 1.0;
  50111. 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);
  50112. };
  50113. /**
  50114. * Main function for light texture projection matrix computing.
  50115. */
  50116. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50117. this._projectionTextureDirty = false;
  50118. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50119. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50120. };
  50121. SpotLight.prototype._buildUniformLayout = function () {
  50122. this._uniformBuffer.addUniform("vLightData", 4);
  50123. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50124. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50125. this._uniformBuffer.addUniform("vLightDirection", 3);
  50126. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50127. this._uniformBuffer.addUniform("depthValues", 2);
  50128. this._uniformBuffer.create();
  50129. };
  50130. /**
  50131. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50132. * @param effect The effect to update
  50133. * @param lightIndex The index of the light in the effect to update
  50134. * @returns The spot light
  50135. */
  50136. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50137. var normalizeDirection;
  50138. if (this.computeTransformedInformation()) {
  50139. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50140. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50141. }
  50142. else {
  50143. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50144. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50145. }
  50146. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50147. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50148. if (this._projectionTextureViewLightDirty) {
  50149. this._computeProjectionTextureViewLightMatrix();
  50150. }
  50151. if (this._projectionTextureProjectionLightDirty) {
  50152. this._computeProjectionTextureProjectionLightMatrix();
  50153. }
  50154. if (this._projectionTextureDirty) {
  50155. this._computeProjectionTextureMatrix();
  50156. }
  50157. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50158. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50159. }
  50160. return this;
  50161. };
  50162. /**
  50163. * Disposes the light and the associated resources.
  50164. */
  50165. SpotLight.prototype.dispose = function () {
  50166. _super.prototype.dispose.call(this);
  50167. if (this._projectionTexture) {
  50168. this._projectionTexture.dispose();
  50169. }
  50170. };
  50171. __decorate([
  50172. BABYLON.serialize()
  50173. ], SpotLight.prototype, "angle", null);
  50174. __decorate([
  50175. BABYLON.serialize()
  50176. ], SpotLight.prototype, "shadowAngleScale", null);
  50177. __decorate([
  50178. BABYLON.serialize()
  50179. ], SpotLight.prototype, "exponent", void 0);
  50180. __decorate([
  50181. BABYLON.serialize()
  50182. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50183. __decorate([
  50184. BABYLON.serialize()
  50185. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50186. __decorate([
  50187. BABYLON.serialize()
  50188. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50189. __decorate([
  50190. BABYLON.serializeAsTexture("projectedLightTexture")
  50191. ], SpotLight.prototype, "_projectionTexture", void 0);
  50192. return SpotLight;
  50193. }(BABYLON.ShadowLight));
  50194. BABYLON.SpotLight = SpotLight;
  50195. })(BABYLON || (BABYLON = {}));
  50196. //# sourceMappingURL=babylon.spotLight.js.map
  50197. var BABYLON;
  50198. (function (BABYLON) {
  50199. /**
  50200. * Class used to override all child animations of a given target
  50201. */
  50202. var AnimationPropertiesOverride = /** @class */ (function () {
  50203. function AnimationPropertiesOverride() {
  50204. /**
  50205. * Gets or sets a value indicating if animation blending must be used
  50206. */
  50207. this.enableBlending = false;
  50208. /**
  50209. * Gets or sets the blending speed to use when enableBlending is true
  50210. */
  50211. this.blendingSpeed = 0.01;
  50212. /**
  50213. * Gets or sets the default loop mode to use
  50214. */
  50215. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50216. }
  50217. return AnimationPropertiesOverride;
  50218. }());
  50219. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50220. })(BABYLON || (BABYLON = {}));
  50221. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50222. var BABYLON;
  50223. (function (BABYLON) {
  50224. /**
  50225. * Represents the range of an animation
  50226. */
  50227. var AnimationRange = /** @class */ (function () {
  50228. /**
  50229. * Initializes the range of an animation
  50230. * @param name The name of the animation range
  50231. * @param from The starting frame of the animation
  50232. * @param to The ending frame of the animation
  50233. */
  50234. function AnimationRange(
  50235. /**The name of the animation range**/
  50236. name,
  50237. /**The starting frame of the animation */
  50238. from,
  50239. /**The ending frame of the animation*/
  50240. to) {
  50241. this.name = name;
  50242. this.from = from;
  50243. this.to = to;
  50244. }
  50245. /**
  50246. * Makes a copy of the animation range
  50247. * @returns A copy of the animation range
  50248. */
  50249. AnimationRange.prototype.clone = function () {
  50250. return new AnimationRange(this.name, this.from, this.to);
  50251. };
  50252. return AnimationRange;
  50253. }());
  50254. BABYLON.AnimationRange = AnimationRange;
  50255. /**
  50256. * Composed of a frame, and an action function
  50257. */
  50258. var AnimationEvent = /** @class */ (function () {
  50259. /**
  50260. * Initializes the animation event
  50261. * @param frame The frame for which the event is triggered
  50262. * @param action The event to perform when triggered
  50263. * @param onlyOnce Specifies if the event should be triggered only once
  50264. */
  50265. function AnimationEvent(
  50266. /** The frame for which the event is triggered **/
  50267. frame,
  50268. /** The event to perform when triggered **/
  50269. action,
  50270. /** Specifies if the event should be triggered only once**/
  50271. onlyOnce) {
  50272. this.frame = frame;
  50273. this.action = action;
  50274. this.onlyOnce = onlyOnce;
  50275. /**
  50276. * Specifies if the animation event is done
  50277. */
  50278. this.isDone = false;
  50279. }
  50280. /** @hidden */
  50281. AnimationEvent.prototype._clone = function () {
  50282. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  50283. };
  50284. return AnimationEvent;
  50285. }());
  50286. BABYLON.AnimationEvent = AnimationEvent;
  50287. /**
  50288. * A cursor which tracks a point on a path
  50289. */
  50290. var PathCursor = /** @class */ (function () {
  50291. /**
  50292. * Initializes the path cursor
  50293. * @param path The path to track
  50294. */
  50295. function PathCursor(path) {
  50296. this.path = path;
  50297. /**
  50298. * Stores path cursor callbacks for when an onchange event is triggered
  50299. */
  50300. this._onchange = new Array();
  50301. /**
  50302. * The value of the path cursor
  50303. */
  50304. this.value = 0;
  50305. /**
  50306. * The animation array of the path cursor
  50307. */
  50308. this.animations = new Array();
  50309. }
  50310. /**
  50311. * Gets the cursor point on the path
  50312. * @returns A point on the path cursor at the cursor location
  50313. */
  50314. PathCursor.prototype.getPoint = function () {
  50315. var point = this.path.getPointAtLengthPosition(this.value);
  50316. return new BABYLON.Vector3(point.x, 0, point.y);
  50317. };
  50318. /**
  50319. * Moves the cursor ahead by the step amount
  50320. * @param step The amount to move the cursor forward
  50321. * @returns This path cursor
  50322. */
  50323. PathCursor.prototype.moveAhead = function (step) {
  50324. if (step === void 0) { step = 0.002; }
  50325. this.move(step);
  50326. return this;
  50327. };
  50328. /**
  50329. * Moves the cursor behind by the step amount
  50330. * @param step The amount to move the cursor back
  50331. * @returns This path cursor
  50332. */
  50333. PathCursor.prototype.moveBack = function (step) {
  50334. if (step === void 0) { step = 0.002; }
  50335. this.move(-step);
  50336. return this;
  50337. };
  50338. /**
  50339. * Moves the cursor by the step amount
  50340. * If the step amount is greater than one, an exception is thrown
  50341. * @param step The amount to move the cursor
  50342. * @returns This path cursor
  50343. */
  50344. PathCursor.prototype.move = function (step) {
  50345. if (Math.abs(step) > 1) {
  50346. throw "step size should be less than 1.";
  50347. }
  50348. this.value += step;
  50349. this.ensureLimits();
  50350. this.raiseOnChange();
  50351. return this;
  50352. };
  50353. /**
  50354. * Ensures that the value is limited between zero and one
  50355. * @returns This path cursor
  50356. */
  50357. PathCursor.prototype.ensureLimits = function () {
  50358. while (this.value > 1) {
  50359. this.value -= 1;
  50360. }
  50361. while (this.value < 0) {
  50362. this.value += 1;
  50363. }
  50364. return this;
  50365. };
  50366. /**
  50367. * Runs onchange callbacks on change (used by the animation engine)
  50368. * @returns This path cursor
  50369. */
  50370. PathCursor.prototype.raiseOnChange = function () {
  50371. var _this = this;
  50372. this._onchange.forEach(function (f) { return f(_this); });
  50373. return this;
  50374. };
  50375. /**
  50376. * Executes a function on change
  50377. * @param f A path cursor onchange callback
  50378. * @returns This path cursor
  50379. */
  50380. PathCursor.prototype.onchange = function (f) {
  50381. this._onchange.push(f);
  50382. return this;
  50383. };
  50384. return PathCursor;
  50385. }());
  50386. BABYLON.PathCursor = PathCursor;
  50387. /**
  50388. * Enum for the animation key frame interpolation type
  50389. */
  50390. var AnimationKeyInterpolation;
  50391. (function (AnimationKeyInterpolation) {
  50392. /**
  50393. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50394. */
  50395. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50396. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50397. /**
  50398. * Class used to store any kind of animation
  50399. */
  50400. var Animation = /** @class */ (function () {
  50401. /**
  50402. * Initializes the animation
  50403. * @param name Name of the animation
  50404. * @param targetProperty Property to animate
  50405. * @param framePerSecond The frames per second of the animation
  50406. * @param dataType The data type of the animation
  50407. * @param loopMode The loop mode of the animation
  50408. * @param enableBlendings Specifies if blending should be enabled
  50409. */
  50410. function Animation(
  50411. /**Name of the animation */
  50412. name,
  50413. /**Property to animate */
  50414. targetProperty,
  50415. /**The frames per second of the animation */
  50416. framePerSecond,
  50417. /**The data type of the animation */
  50418. dataType,
  50419. /**The loop mode of the animation */
  50420. loopMode,
  50421. /**Specifies if blending should be enabled */
  50422. enableBlending) {
  50423. this.name = name;
  50424. this.targetProperty = targetProperty;
  50425. this.framePerSecond = framePerSecond;
  50426. this.dataType = dataType;
  50427. this.loopMode = loopMode;
  50428. this.enableBlending = enableBlending;
  50429. /**
  50430. * @hidden Internal use only
  50431. */
  50432. this._runtimeAnimations = new Array();
  50433. /**
  50434. * The set of event that will be linked to this animation
  50435. */
  50436. this._events = new Array();
  50437. /**
  50438. * Stores the blending speed of the animation
  50439. */
  50440. this.blendingSpeed = 0.01;
  50441. /**
  50442. * Stores the animation ranges for the animation
  50443. */
  50444. this._ranges = {};
  50445. this.targetPropertyPath = targetProperty.split(".");
  50446. this.dataType = dataType;
  50447. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50448. }
  50449. /**
  50450. * @hidden Internal use
  50451. */
  50452. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50453. var dataType = undefined;
  50454. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50455. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50456. }
  50457. else if (from instanceof BABYLON.Quaternion) {
  50458. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50459. }
  50460. else if (from instanceof BABYLON.Vector3) {
  50461. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50462. }
  50463. else if (from instanceof BABYLON.Vector2) {
  50464. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50465. }
  50466. else if (from instanceof BABYLON.Color3) {
  50467. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50468. }
  50469. else if (from instanceof BABYLON.Size) {
  50470. dataType = Animation.ANIMATIONTYPE_SIZE;
  50471. }
  50472. if (dataType == undefined) {
  50473. return null;
  50474. }
  50475. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50476. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50477. animation.setKeys(keys);
  50478. if (easingFunction !== undefined) {
  50479. animation.setEasingFunction(easingFunction);
  50480. }
  50481. return animation;
  50482. };
  50483. /**
  50484. * Sets up an animation
  50485. * @param property The property to animate
  50486. * @param animationType The animation type to apply
  50487. * @param framePerSecond The frames per second of the animation
  50488. * @param easingFunction The easing function used in the animation
  50489. * @returns The created animation
  50490. */
  50491. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50492. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50493. animation.setEasingFunction(easingFunction);
  50494. return animation;
  50495. };
  50496. /**
  50497. * Create and start an animation on a node
  50498. * @param name defines the name of the global animation that will be run on all nodes
  50499. * @param node defines the root node where the animation will take place
  50500. * @param targetProperty defines property to animate
  50501. * @param framePerSecond defines the number of frame per second yo use
  50502. * @param totalFrame defines the number of frames in total
  50503. * @param from defines the initial value
  50504. * @param to defines the final value
  50505. * @param loopMode defines which loop mode you want to use (off by default)
  50506. * @param easingFunction defines the easing function to use (linear by default)
  50507. * @param onAnimationEnd defines the callback to call when animation end
  50508. * @returns the animatable created for this animation
  50509. */
  50510. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50511. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50512. if (!animation) {
  50513. return null;
  50514. }
  50515. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50516. };
  50517. /**
  50518. * Create and start an animation on a node and its descendants
  50519. * @param name defines the name of the global animation that will be run on all nodes
  50520. * @param node defines the root node where the animation will take place
  50521. * @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
  50522. * @param targetProperty defines property to animate
  50523. * @param framePerSecond defines the number of frame per second to use
  50524. * @param totalFrame defines the number of frames in total
  50525. * @param from defines the initial value
  50526. * @param to defines the final value
  50527. * @param loopMode defines which loop mode you want to use (off by default)
  50528. * @param easingFunction defines the easing function to use (linear by default)
  50529. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50530. * @returns the list of animatables created for all nodes
  50531. * @example https://www.babylonjs-playground.com/#MH0VLI
  50532. */
  50533. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50534. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50535. if (!animation) {
  50536. return null;
  50537. }
  50538. var scene = node.getScene();
  50539. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50540. };
  50541. /**
  50542. * Creates a new animation, merges it with the existing animations and starts it
  50543. * @param name Name of the animation
  50544. * @param node Node which contains the scene that begins the animations
  50545. * @param targetProperty Specifies which property to animate
  50546. * @param framePerSecond The frames per second of the animation
  50547. * @param totalFrame The total number of frames
  50548. * @param from The frame at the beginning of the animation
  50549. * @param to The frame at the end of the animation
  50550. * @param loopMode Specifies the loop mode of the animation
  50551. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50552. * @param onAnimationEnd Callback to run once the animation is complete
  50553. * @returns Nullable animation
  50554. */
  50555. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50556. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50557. if (!animation) {
  50558. return null;
  50559. }
  50560. node.animations.push(animation);
  50561. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50562. };
  50563. /**
  50564. * Transition property of the Camera to the target Value
  50565. * @param property The property to transition
  50566. * @param targetValue The target Value of the property
  50567. * @param host The object where the property to animate belongs
  50568. * @param scene Scene used to run the animation
  50569. * @param frameRate Framerate (in frame/s) to use
  50570. * @param transition The transition type we want to use
  50571. * @param duration The duration of the animation, in milliseconds
  50572. * @param onAnimationEnd Callback trigger at the end of the animation
  50573. * @returns Nullable animation
  50574. */
  50575. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50576. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50577. if (duration <= 0) {
  50578. host[property] = targetValue;
  50579. if (onAnimationEnd) {
  50580. onAnimationEnd();
  50581. }
  50582. return null;
  50583. }
  50584. var endFrame = frameRate * (duration / 1000);
  50585. transition.setKeys([{
  50586. frame: 0,
  50587. value: host[property].clone ? host[property].clone() : host[property]
  50588. },
  50589. {
  50590. frame: endFrame,
  50591. value: targetValue
  50592. }]);
  50593. if (!host.animations) {
  50594. host.animations = [];
  50595. }
  50596. host.animations.push(transition);
  50597. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50598. animation.onAnimationEnd = onAnimationEnd;
  50599. return animation;
  50600. };
  50601. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50602. /**
  50603. * Return the array of runtime animations currently using this animation
  50604. */
  50605. get: function () {
  50606. return this._runtimeAnimations;
  50607. },
  50608. enumerable: true,
  50609. configurable: true
  50610. });
  50611. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50612. /**
  50613. * Specifies if any of the runtime animations are currently running
  50614. */
  50615. get: function () {
  50616. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50617. var runtimeAnimation = _a[_i];
  50618. if (!runtimeAnimation.isStopped) {
  50619. return true;
  50620. }
  50621. }
  50622. return false;
  50623. },
  50624. enumerable: true,
  50625. configurable: true
  50626. });
  50627. // Methods
  50628. /**
  50629. * Converts the animation to a string
  50630. * @param fullDetails support for multiple levels of logging within scene loading
  50631. * @returns String form of the animation
  50632. */
  50633. Animation.prototype.toString = function (fullDetails) {
  50634. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50635. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50636. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50637. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50638. if (fullDetails) {
  50639. ret += ", Ranges: {";
  50640. var first = true;
  50641. for (var name in this._ranges) {
  50642. if (first) {
  50643. ret += ", ";
  50644. first = false;
  50645. }
  50646. ret += name;
  50647. }
  50648. ret += "}";
  50649. }
  50650. return ret;
  50651. };
  50652. /**
  50653. * Add an event to this animation
  50654. * @param event Event to add
  50655. */
  50656. Animation.prototype.addEvent = function (event) {
  50657. this._events.push(event);
  50658. };
  50659. /**
  50660. * Remove all events found at the given frame
  50661. * @param frame The frame to remove events from
  50662. */
  50663. Animation.prototype.removeEvents = function (frame) {
  50664. for (var index = 0; index < this._events.length; index++) {
  50665. if (this._events[index].frame === frame) {
  50666. this._events.splice(index, 1);
  50667. index--;
  50668. }
  50669. }
  50670. };
  50671. /**
  50672. * Retrieves all the events from the animation
  50673. * @returns Events from the animation
  50674. */
  50675. Animation.prototype.getEvents = function () {
  50676. return this._events;
  50677. };
  50678. /**
  50679. * Creates an animation range
  50680. * @param name Name of the animation range
  50681. * @param from Starting frame of the animation range
  50682. * @param to Ending frame of the animation
  50683. */
  50684. Animation.prototype.createRange = function (name, from, to) {
  50685. // check name not already in use; could happen for bones after serialized
  50686. if (!this._ranges[name]) {
  50687. this._ranges[name] = new AnimationRange(name, from, to);
  50688. }
  50689. };
  50690. /**
  50691. * Deletes an animation range by name
  50692. * @param name Name of the animation range to delete
  50693. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50694. */
  50695. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50696. if (deleteFrames === void 0) { deleteFrames = true; }
  50697. var range = this._ranges[name];
  50698. if (!range) {
  50699. return;
  50700. }
  50701. if (deleteFrames) {
  50702. var from = range.from;
  50703. var to = range.to;
  50704. // this loop MUST go high to low for multiple splices to work
  50705. for (var key = this._keys.length - 1; key >= 0; key--) {
  50706. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50707. this._keys.splice(key, 1);
  50708. }
  50709. }
  50710. }
  50711. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50712. };
  50713. /**
  50714. * Gets the animation range by name, or null if not defined
  50715. * @param name Name of the animation range
  50716. * @returns Nullable animation range
  50717. */
  50718. Animation.prototype.getRange = function (name) {
  50719. return this._ranges[name];
  50720. };
  50721. /**
  50722. * Gets the key frames from the animation
  50723. * @returns The key frames of the animation
  50724. */
  50725. Animation.prototype.getKeys = function () {
  50726. return this._keys;
  50727. };
  50728. /**
  50729. * Gets the highest frame rate of the animation
  50730. * @returns Highest frame rate of the animation
  50731. */
  50732. Animation.prototype.getHighestFrame = function () {
  50733. var ret = 0;
  50734. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50735. if (ret < this._keys[key].frame) {
  50736. ret = this._keys[key].frame;
  50737. }
  50738. }
  50739. return ret;
  50740. };
  50741. /**
  50742. * Gets the easing function of the animation
  50743. * @returns Easing function of the animation
  50744. */
  50745. Animation.prototype.getEasingFunction = function () {
  50746. return this._easingFunction;
  50747. };
  50748. /**
  50749. * Sets the easing function of the animation
  50750. * @param easingFunction A custom mathematical formula for animation
  50751. */
  50752. Animation.prototype.setEasingFunction = function (easingFunction) {
  50753. this._easingFunction = easingFunction;
  50754. };
  50755. /**
  50756. * Interpolates a scalar linearly
  50757. * @param startValue Start value of the animation curve
  50758. * @param endValue End value of the animation curve
  50759. * @param gradient Scalar amount to interpolate
  50760. * @returns Interpolated scalar value
  50761. */
  50762. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50763. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50764. };
  50765. /**
  50766. * Interpolates a scalar cubically
  50767. * @param startValue Start value of the animation curve
  50768. * @param outTangent End tangent of the animation
  50769. * @param endValue End value of the animation curve
  50770. * @param inTangent Start tangent of the animation curve
  50771. * @param gradient Scalar amount to interpolate
  50772. * @returns Interpolated scalar value
  50773. */
  50774. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50775. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50776. };
  50777. /**
  50778. * Interpolates a quaternion using a spherical linear interpolation
  50779. * @param startValue Start value of the animation curve
  50780. * @param endValue End value of the animation curve
  50781. * @param gradient Scalar amount to interpolate
  50782. * @returns Interpolated quaternion value
  50783. */
  50784. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50785. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50786. };
  50787. /**
  50788. * Interpolates a quaternion cubically
  50789. * @param startValue Start value of the animation curve
  50790. * @param outTangent End tangent of the animation curve
  50791. * @param endValue End value of the animation curve
  50792. * @param inTangent Start tangent of the animation curve
  50793. * @param gradient Scalar amount to interpolate
  50794. * @returns Interpolated quaternion value
  50795. */
  50796. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50797. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50798. };
  50799. /**
  50800. * Interpolates a Vector3 linearl
  50801. * @param startValue Start value of the animation curve
  50802. * @param endValue End value of the animation curve
  50803. * @param gradient Scalar amount to interpolate
  50804. * @returns Interpolated scalar value
  50805. */
  50806. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50807. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50808. };
  50809. /**
  50810. * Interpolates a Vector3 cubically
  50811. * @param startValue Start value of the animation curve
  50812. * @param outTangent End tangent of the animation
  50813. * @param endValue End value of the animation curve
  50814. * @param inTangent Start tangent of the animation curve
  50815. * @param gradient Scalar amount to interpolate
  50816. * @returns InterpolatedVector3 value
  50817. */
  50818. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50819. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50820. };
  50821. /**
  50822. * Interpolates a Vector2 linearly
  50823. * @param startValue Start value of the animation curve
  50824. * @param endValue End value of the animation curve
  50825. * @param gradient Scalar amount to interpolate
  50826. * @returns Interpolated Vector2 value
  50827. */
  50828. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50829. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50830. };
  50831. /**
  50832. * Interpolates a Vector2 cubically
  50833. * @param startValue Start value of the animation curve
  50834. * @param outTangent End tangent of the animation
  50835. * @param endValue End value of the animation curve
  50836. * @param inTangent Start tangent of the animation curve
  50837. * @param gradient Scalar amount to interpolate
  50838. * @returns Interpolated Vector2 value
  50839. */
  50840. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50841. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50842. };
  50843. /**
  50844. * Interpolates a size linearly
  50845. * @param startValue Start value of the animation curve
  50846. * @param endValue End value of the animation curve
  50847. * @param gradient Scalar amount to interpolate
  50848. * @returns Interpolated Size value
  50849. */
  50850. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50851. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50852. };
  50853. /**
  50854. * Interpolates a Color3 linearly
  50855. * @param startValue Start value of the animation curve
  50856. * @param endValue End value of the animation curve
  50857. * @param gradient Scalar amount to interpolate
  50858. * @returns Interpolated Color3 value
  50859. */
  50860. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50861. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50862. };
  50863. /**
  50864. * @hidden Internal use only
  50865. */
  50866. Animation.prototype._getKeyValue = function (value) {
  50867. if (typeof value === "function") {
  50868. return value();
  50869. }
  50870. return value;
  50871. };
  50872. /**
  50873. * @hidden Internal use only
  50874. */
  50875. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50876. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50877. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50878. }
  50879. var keys = this.getKeys();
  50880. // Try to get a hash to find the right key
  50881. 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));
  50882. if (keys[startKeyIndex].frame >= currentFrame) {
  50883. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50884. startKeyIndex--;
  50885. }
  50886. }
  50887. for (var key = startKeyIndex; key < keys.length; key++) {
  50888. var endKey = keys[key + 1];
  50889. if (endKey.frame >= currentFrame) {
  50890. var startKey = keys[key];
  50891. var startValue = this._getKeyValue(startKey.value);
  50892. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50893. return startValue;
  50894. }
  50895. var endValue = this._getKeyValue(endKey.value);
  50896. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50897. var frameDelta = endKey.frame - startKey.frame;
  50898. // gradient : percent of currentFrame between the frame inf and the frame sup
  50899. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50900. // check for easingFunction and correction of gradient
  50901. var easingFunction = this.getEasingFunction();
  50902. if (easingFunction != null) {
  50903. gradient = easingFunction.ease(gradient);
  50904. }
  50905. switch (this.dataType) {
  50906. // Float
  50907. case Animation.ANIMATIONTYPE_FLOAT:
  50908. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50909. switch (loopMode) {
  50910. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50911. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50912. return floatValue;
  50913. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50914. return offsetValue * repeatCount + floatValue;
  50915. }
  50916. break;
  50917. // Quaternion
  50918. case Animation.ANIMATIONTYPE_QUATERNION:
  50919. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50920. switch (loopMode) {
  50921. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50922. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50923. return quatValue;
  50924. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50925. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50926. }
  50927. return quatValue;
  50928. // Vector3
  50929. case Animation.ANIMATIONTYPE_VECTOR3:
  50930. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50931. switch (loopMode) {
  50932. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50933. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50934. return vec3Value;
  50935. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50936. return vec3Value.add(offsetValue.scale(repeatCount));
  50937. }
  50938. // Vector2
  50939. case Animation.ANIMATIONTYPE_VECTOR2:
  50940. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50941. switch (loopMode) {
  50942. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50943. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50944. return vec2Value;
  50945. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50946. return vec2Value.add(offsetValue.scale(repeatCount));
  50947. }
  50948. // Size
  50949. case Animation.ANIMATIONTYPE_SIZE:
  50950. switch (loopMode) {
  50951. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50952. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50953. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50954. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50955. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50956. }
  50957. // Color3
  50958. case Animation.ANIMATIONTYPE_COLOR3:
  50959. switch (loopMode) {
  50960. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50961. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50962. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50963. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50964. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50965. }
  50966. // Matrix
  50967. case Animation.ANIMATIONTYPE_MATRIX:
  50968. switch (loopMode) {
  50969. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50970. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50971. if (Animation.AllowMatricesInterpolation) {
  50972. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50973. }
  50974. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50975. return startValue;
  50976. }
  50977. default:
  50978. break;
  50979. }
  50980. break;
  50981. }
  50982. }
  50983. return this._getKeyValue(keys[keys.length - 1].value);
  50984. };
  50985. /**
  50986. * Defines the function to use to interpolate matrices
  50987. * @param startValue defines the start matrix
  50988. * @param endValue defines the end matrix
  50989. * @param gradient defines the gradient between both matrices
  50990. * @param result defines an optional target matrix where to store the interpolation
  50991. * @returns the interpolated matrix
  50992. */
  50993. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50994. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50995. if (result) {
  50996. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50997. return result;
  50998. }
  50999. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51000. }
  51001. if (result) {
  51002. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51003. return result;
  51004. }
  51005. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51006. };
  51007. /**
  51008. * Makes a copy of the animation
  51009. * @returns Cloned animation
  51010. */
  51011. Animation.prototype.clone = function () {
  51012. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51013. clone.enableBlending = this.enableBlending;
  51014. clone.blendingSpeed = this.blendingSpeed;
  51015. if (this._keys) {
  51016. clone.setKeys(this._keys);
  51017. }
  51018. if (this._ranges) {
  51019. clone._ranges = {};
  51020. for (var name in this._ranges) {
  51021. var range = this._ranges[name];
  51022. if (!range) {
  51023. continue;
  51024. }
  51025. clone._ranges[name] = range.clone();
  51026. }
  51027. }
  51028. return clone;
  51029. };
  51030. /**
  51031. * Sets the key frames of the animation
  51032. * @param values The animation key frames to set
  51033. */
  51034. Animation.prototype.setKeys = function (values) {
  51035. this._keys = values.slice(0);
  51036. };
  51037. /**
  51038. * Serializes the animation to an object
  51039. * @returns Serialized object
  51040. */
  51041. Animation.prototype.serialize = function () {
  51042. var serializationObject = {};
  51043. serializationObject.name = this.name;
  51044. serializationObject.property = this.targetProperty;
  51045. serializationObject.framePerSecond = this.framePerSecond;
  51046. serializationObject.dataType = this.dataType;
  51047. serializationObject.loopBehavior = this.loopMode;
  51048. serializationObject.enableBlending = this.enableBlending;
  51049. serializationObject.blendingSpeed = this.blendingSpeed;
  51050. var dataType = this.dataType;
  51051. serializationObject.keys = [];
  51052. var keys = this.getKeys();
  51053. for (var index = 0; index < keys.length; index++) {
  51054. var animationKey = keys[index];
  51055. var key = {};
  51056. key.frame = animationKey.frame;
  51057. switch (dataType) {
  51058. case Animation.ANIMATIONTYPE_FLOAT:
  51059. key.values = [animationKey.value];
  51060. break;
  51061. case Animation.ANIMATIONTYPE_QUATERNION:
  51062. case Animation.ANIMATIONTYPE_MATRIX:
  51063. case Animation.ANIMATIONTYPE_VECTOR3:
  51064. case Animation.ANIMATIONTYPE_COLOR3:
  51065. key.values = animationKey.value.asArray();
  51066. break;
  51067. }
  51068. serializationObject.keys.push(key);
  51069. }
  51070. serializationObject.ranges = [];
  51071. for (var name in this._ranges) {
  51072. var source = this._ranges[name];
  51073. if (!source) {
  51074. continue;
  51075. }
  51076. var range = {};
  51077. range.name = name;
  51078. range.from = source.from;
  51079. range.to = source.to;
  51080. serializationObject.ranges.push(range);
  51081. }
  51082. return serializationObject;
  51083. };
  51084. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51085. /**
  51086. * Get the float animation type
  51087. */
  51088. get: function () {
  51089. return Animation._ANIMATIONTYPE_FLOAT;
  51090. },
  51091. enumerable: true,
  51092. configurable: true
  51093. });
  51094. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51095. /**
  51096. * Get the Vector3 animation type
  51097. */
  51098. get: function () {
  51099. return Animation._ANIMATIONTYPE_VECTOR3;
  51100. },
  51101. enumerable: true,
  51102. configurable: true
  51103. });
  51104. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51105. /**
  51106. * Get the Vectpr2 animation type
  51107. */
  51108. get: function () {
  51109. return Animation._ANIMATIONTYPE_VECTOR2;
  51110. },
  51111. enumerable: true,
  51112. configurable: true
  51113. });
  51114. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51115. /**
  51116. * Get the Size animation type
  51117. */
  51118. get: function () {
  51119. return Animation._ANIMATIONTYPE_SIZE;
  51120. },
  51121. enumerable: true,
  51122. configurable: true
  51123. });
  51124. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51125. /**
  51126. * Get the Quaternion animation type
  51127. */
  51128. get: function () {
  51129. return Animation._ANIMATIONTYPE_QUATERNION;
  51130. },
  51131. enumerable: true,
  51132. configurable: true
  51133. });
  51134. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51135. /**
  51136. * Get the Matrix animation type
  51137. */
  51138. get: function () {
  51139. return Animation._ANIMATIONTYPE_MATRIX;
  51140. },
  51141. enumerable: true,
  51142. configurable: true
  51143. });
  51144. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51145. /**
  51146. * Get the Color3 animation type
  51147. */
  51148. get: function () {
  51149. return Animation._ANIMATIONTYPE_COLOR3;
  51150. },
  51151. enumerable: true,
  51152. configurable: true
  51153. });
  51154. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51155. /**
  51156. * Get the Relative Loop Mode
  51157. */
  51158. get: function () {
  51159. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51160. },
  51161. enumerable: true,
  51162. configurable: true
  51163. });
  51164. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51165. /**
  51166. * Get the Cycle Loop Mode
  51167. */
  51168. get: function () {
  51169. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51170. },
  51171. enumerable: true,
  51172. configurable: true
  51173. });
  51174. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51175. /**
  51176. * Get the Constant Loop Mode
  51177. */
  51178. get: function () {
  51179. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51180. },
  51181. enumerable: true,
  51182. configurable: true
  51183. });
  51184. /** @hidden */
  51185. Animation._UniversalLerp = function (left, right, amount) {
  51186. var constructor = left.constructor;
  51187. if (constructor.Lerp) { // Lerp supported
  51188. return constructor.Lerp(left, right, amount);
  51189. }
  51190. else if (constructor.Slerp) { // Slerp supported
  51191. return constructor.Slerp(left, right, amount);
  51192. }
  51193. else if (left.toFixed) { // Number
  51194. return left * (1.0 - amount) + amount * right;
  51195. }
  51196. else { // Blending not supported
  51197. return right;
  51198. }
  51199. };
  51200. /**
  51201. * Parses an animation object and creates an animation
  51202. * @param parsedAnimation Parsed animation object
  51203. * @returns Animation object
  51204. */
  51205. Animation.Parse = function (parsedAnimation) {
  51206. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51207. var dataType = parsedAnimation.dataType;
  51208. var keys = [];
  51209. var data;
  51210. var index;
  51211. if (parsedAnimation.enableBlending) {
  51212. animation.enableBlending = parsedAnimation.enableBlending;
  51213. }
  51214. if (parsedAnimation.blendingSpeed) {
  51215. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51216. }
  51217. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51218. var key = parsedAnimation.keys[index];
  51219. var inTangent;
  51220. var outTangent;
  51221. switch (dataType) {
  51222. case Animation.ANIMATIONTYPE_FLOAT:
  51223. data = key.values[0];
  51224. if (key.values.length >= 1) {
  51225. inTangent = key.values[1];
  51226. }
  51227. if (key.values.length >= 2) {
  51228. outTangent = key.values[2];
  51229. }
  51230. break;
  51231. case Animation.ANIMATIONTYPE_QUATERNION:
  51232. data = BABYLON.Quaternion.FromArray(key.values);
  51233. if (key.values.length >= 8) {
  51234. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51235. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51236. inTangent = _inTangent;
  51237. }
  51238. }
  51239. if (key.values.length >= 12) {
  51240. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51241. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51242. outTangent = _outTangent;
  51243. }
  51244. }
  51245. break;
  51246. case Animation.ANIMATIONTYPE_MATRIX:
  51247. data = BABYLON.Matrix.FromArray(key.values);
  51248. break;
  51249. case Animation.ANIMATIONTYPE_COLOR3:
  51250. data = BABYLON.Color3.FromArray(key.values);
  51251. break;
  51252. case Animation.ANIMATIONTYPE_VECTOR3:
  51253. default:
  51254. data = BABYLON.Vector3.FromArray(key.values);
  51255. break;
  51256. }
  51257. var keyData = {};
  51258. keyData.frame = key.frame;
  51259. keyData.value = data;
  51260. if (inTangent != undefined) {
  51261. keyData.inTangent = inTangent;
  51262. }
  51263. if (outTangent != undefined) {
  51264. keyData.outTangent = outTangent;
  51265. }
  51266. keys.push(keyData);
  51267. }
  51268. animation.setKeys(keys);
  51269. if (parsedAnimation.ranges) {
  51270. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51271. data = parsedAnimation.ranges[index];
  51272. animation.createRange(data.name, data.from, data.to);
  51273. }
  51274. }
  51275. return animation;
  51276. };
  51277. /**
  51278. * Appends the serialized animations from the source animations
  51279. * @param source Source containing the animations
  51280. * @param destination Target to store the animations
  51281. */
  51282. Animation.AppendSerializedAnimations = function (source, destination) {
  51283. if (source.animations) {
  51284. destination.animations = [];
  51285. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51286. var animation = source.animations[animationIndex];
  51287. destination.animations.push(animation.serialize());
  51288. }
  51289. }
  51290. };
  51291. /**
  51292. * Use matrix interpolation instead of using direct key value when animating matrices
  51293. */
  51294. Animation.AllowMatricesInterpolation = false;
  51295. /**
  51296. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51297. */
  51298. Animation.AllowMatrixDecomposeForInterpolation = true;
  51299. // Statics
  51300. /**
  51301. * Float animation type
  51302. */
  51303. Animation._ANIMATIONTYPE_FLOAT = 0;
  51304. /**
  51305. * Vector3 animation type
  51306. */
  51307. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51308. /**
  51309. * Quaternion animation type
  51310. */
  51311. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51312. /**
  51313. * Matrix animation type
  51314. */
  51315. Animation._ANIMATIONTYPE_MATRIX = 3;
  51316. /**
  51317. * Color3 animation type
  51318. */
  51319. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51320. /**
  51321. * Vector2 animation type
  51322. */
  51323. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51324. /**
  51325. * Size animation type
  51326. */
  51327. Animation._ANIMATIONTYPE_SIZE = 6;
  51328. /**
  51329. * Relative Loop Mode
  51330. */
  51331. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51332. /**
  51333. * Cycle Loop Mode
  51334. */
  51335. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51336. /**
  51337. * Constant Loop Mode
  51338. */
  51339. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51340. return Animation;
  51341. }());
  51342. BABYLON.Animation = Animation;
  51343. })(BABYLON || (BABYLON = {}));
  51344. //# sourceMappingURL=babylon.animation.js.map
  51345. var BABYLON;
  51346. (function (BABYLON) {
  51347. /**
  51348. * This class defines the direct association between an animation and a target
  51349. */
  51350. var TargetedAnimation = /** @class */ (function () {
  51351. function TargetedAnimation() {
  51352. }
  51353. return TargetedAnimation;
  51354. }());
  51355. BABYLON.TargetedAnimation = TargetedAnimation;
  51356. /**
  51357. * Use this class to create coordinated animations on multiple targets
  51358. */
  51359. var AnimationGroup = /** @class */ (function () {
  51360. function AnimationGroup(name, scene) {
  51361. if (scene === void 0) { scene = null; }
  51362. this.name = name;
  51363. this._targetedAnimations = new Array();
  51364. this._animatables = new Array();
  51365. this._from = Number.MAX_VALUE;
  51366. this._to = -Number.MAX_VALUE;
  51367. this._speedRatio = 1;
  51368. this.onAnimationEndObservable = new BABYLON.Observable();
  51369. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51370. this._scene.animationGroups.push(this);
  51371. }
  51372. Object.defineProperty(AnimationGroup.prototype, "from", {
  51373. /**
  51374. * Gets the first frame
  51375. */
  51376. get: function () {
  51377. return this._from;
  51378. },
  51379. enumerable: true,
  51380. configurable: true
  51381. });
  51382. Object.defineProperty(AnimationGroup.prototype, "to", {
  51383. /**
  51384. * Gets the last frame
  51385. */
  51386. get: function () {
  51387. return this._to;
  51388. },
  51389. enumerable: true,
  51390. configurable: true
  51391. });
  51392. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51393. /**
  51394. * Define if the animations are started
  51395. */
  51396. get: function () {
  51397. return this._isStarted;
  51398. },
  51399. enumerable: true,
  51400. configurable: true
  51401. });
  51402. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51403. /**
  51404. * Gets or sets the speed ratio to use for all animations
  51405. */
  51406. get: function () {
  51407. return this._speedRatio;
  51408. },
  51409. /**
  51410. * Gets or sets the speed ratio to use for all animations
  51411. */
  51412. set: function (value) {
  51413. if (this._speedRatio === value) {
  51414. return;
  51415. }
  51416. this._speedRatio = value;
  51417. for (var index = 0; index < this._animatables.length; index++) {
  51418. var animatable = this._animatables[index];
  51419. animatable.speedRatio = this._speedRatio;
  51420. }
  51421. },
  51422. enumerable: true,
  51423. configurable: true
  51424. });
  51425. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51426. /**
  51427. * Gets the targeted animations for this animation group
  51428. */
  51429. get: function () {
  51430. return this._targetedAnimations;
  51431. },
  51432. enumerable: true,
  51433. configurable: true
  51434. });
  51435. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51436. /**
  51437. * returning the list of animatables controlled by this animation group.
  51438. */
  51439. get: function () {
  51440. return this._animatables;
  51441. },
  51442. enumerable: true,
  51443. configurable: true
  51444. });
  51445. /**
  51446. * Add an animation (with its target) in the group
  51447. * @param animation defines the animation we want to add
  51448. * @param target defines the target of the animation
  51449. * @returns the {BABYLON.TargetedAnimation} object
  51450. */
  51451. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51452. var targetedAnimation = {
  51453. animation: animation,
  51454. target: target
  51455. };
  51456. var keys = animation.getKeys();
  51457. if (this._from > keys[0].frame) {
  51458. this._from = keys[0].frame;
  51459. }
  51460. if (this._to < keys[keys.length - 1].frame) {
  51461. this._to = keys[keys.length - 1].frame;
  51462. }
  51463. this._targetedAnimations.push(targetedAnimation);
  51464. return targetedAnimation;
  51465. };
  51466. /**
  51467. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51468. * It can add constant keys at begin or end
  51469. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51470. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51471. */
  51472. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51473. if (beginFrame === void 0) { beginFrame = null; }
  51474. if (endFrame === void 0) { endFrame = null; }
  51475. if (beginFrame == null)
  51476. beginFrame = this._from;
  51477. if (endFrame == null)
  51478. endFrame = this._to;
  51479. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51480. var targetedAnimation = this._targetedAnimations[index];
  51481. var keys = targetedAnimation.animation.getKeys();
  51482. var startKey = keys[0];
  51483. var endKey = keys[keys.length - 1];
  51484. if (startKey.frame > beginFrame) {
  51485. var newKey = {
  51486. frame: beginFrame,
  51487. value: startKey.value,
  51488. inTangent: startKey.inTangent,
  51489. outTangent: startKey.outTangent,
  51490. interpolation: startKey.interpolation
  51491. };
  51492. keys.splice(0, 0, newKey);
  51493. }
  51494. if (endKey.frame < endFrame) {
  51495. var newKey = {
  51496. frame: endFrame,
  51497. value: endKey.value,
  51498. inTangent: endKey.outTangent,
  51499. outTangent: endKey.outTangent,
  51500. interpolation: endKey.interpolation
  51501. };
  51502. keys.push(newKey);
  51503. }
  51504. }
  51505. this._from = beginFrame;
  51506. this._to = endFrame;
  51507. return this;
  51508. };
  51509. /**
  51510. * Start all animations on given targets
  51511. * @param loop defines if animations must loop
  51512. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51513. * @param from defines the from key (optional)
  51514. * @param to defines the to key (optional)
  51515. * @returns the current animation group
  51516. */
  51517. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51518. var _this = this;
  51519. if (loop === void 0) { loop = false; }
  51520. if (speedRatio === void 0) { speedRatio = 1; }
  51521. if (this._isStarted || this._targetedAnimations.length === 0) {
  51522. return this;
  51523. }
  51524. var _loop_1 = function (targetedAnimation) {
  51525. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51526. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51527. }));
  51528. };
  51529. var this_1 = this;
  51530. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51531. var targetedAnimation = _a[_i];
  51532. _loop_1(targetedAnimation);
  51533. }
  51534. this._speedRatio = speedRatio;
  51535. this._isStarted = true;
  51536. return this;
  51537. };
  51538. /**
  51539. * Pause all animations
  51540. */
  51541. AnimationGroup.prototype.pause = function () {
  51542. if (!this._isStarted) {
  51543. return this;
  51544. }
  51545. for (var index = 0; index < this._animatables.length; index++) {
  51546. var animatable = this._animatables[index];
  51547. animatable.pause();
  51548. }
  51549. return this;
  51550. };
  51551. /**
  51552. * Play all animations to initial state
  51553. * This function will start() the animations if they were not started or will restart() them if they were paused
  51554. * @param loop defines if animations must loop
  51555. */
  51556. AnimationGroup.prototype.play = function (loop) {
  51557. if (this.isStarted) {
  51558. if (loop !== undefined) {
  51559. for (var index = 0; index < this._animatables.length; index++) {
  51560. var animatable = this._animatables[index];
  51561. animatable.loopAnimation = loop;
  51562. }
  51563. }
  51564. this.restart();
  51565. }
  51566. else {
  51567. this.start(loop, this._speedRatio);
  51568. }
  51569. return this;
  51570. };
  51571. /**
  51572. * Reset all animations to initial state
  51573. */
  51574. AnimationGroup.prototype.reset = function () {
  51575. if (!this._isStarted) {
  51576. return this;
  51577. }
  51578. for (var index = 0; index < this._animatables.length; index++) {
  51579. var animatable = this._animatables[index];
  51580. animatable.reset();
  51581. }
  51582. return this;
  51583. };
  51584. /**
  51585. * Restart animations from key 0
  51586. */
  51587. AnimationGroup.prototype.restart = function () {
  51588. if (!this._isStarted) {
  51589. return this;
  51590. }
  51591. for (var index = 0; index < this._animatables.length; index++) {
  51592. var animatable = this._animatables[index];
  51593. animatable.restart();
  51594. }
  51595. return this;
  51596. };
  51597. /**
  51598. * Stop all animations
  51599. */
  51600. AnimationGroup.prototype.stop = function () {
  51601. if (!this._isStarted) {
  51602. return this;
  51603. }
  51604. for (var index = 0; index < this._animatables.length; index++) {
  51605. var animatable = this._animatables[index];
  51606. animatable.stop();
  51607. }
  51608. this._isStarted = false;
  51609. return this;
  51610. };
  51611. /**
  51612. * Set animation weight for all animatables
  51613. * @param weight defines the weight to use
  51614. * @return the animationGroup
  51615. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51616. */
  51617. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51618. for (var index = 0; index < this._animatables.length; index++) {
  51619. var animatable = this._animatables[index];
  51620. animatable.weight = weight;
  51621. }
  51622. return this;
  51623. };
  51624. /**
  51625. * Synchronize and normalize all animatables with a source animatable
  51626. * @param root defines the root animatable to synchronize with
  51627. * @return the animationGroup
  51628. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51629. */
  51630. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51631. for (var index = 0; index < this._animatables.length; index++) {
  51632. var animatable = this._animatables[index];
  51633. animatable.syncWith(root);
  51634. }
  51635. return this;
  51636. };
  51637. /**
  51638. * Goes to a specific frame in this animation group
  51639. * @param frame the frame number to go to
  51640. * @return the animationGroup
  51641. */
  51642. AnimationGroup.prototype.goToFrame = function (frame) {
  51643. if (!this._isStarted) {
  51644. return this;
  51645. }
  51646. for (var index = 0; index < this._animatables.length; index++) {
  51647. var animatable = this._animatables[index];
  51648. animatable.goToFrame(frame);
  51649. }
  51650. return this;
  51651. };
  51652. /**
  51653. * Dispose all associated resources
  51654. */
  51655. AnimationGroup.prototype.dispose = function () {
  51656. this._targetedAnimations = [];
  51657. this._animatables = [];
  51658. var index = this._scene.animationGroups.indexOf(this);
  51659. if (index > -1) {
  51660. this._scene.animationGroups.splice(index, 1);
  51661. }
  51662. };
  51663. return AnimationGroup;
  51664. }());
  51665. BABYLON.AnimationGroup = AnimationGroup;
  51666. })(BABYLON || (BABYLON = {}));
  51667. //# sourceMappingURL=babylon.animationGroup.js.map
  51668. var BABYLON;
  51669. (function (BABYLON) {
  51670. /**
  51671. * Defines a runtime animation
  51672. */
  51673. var RuntimeAnimation = /** @class */ (function () {
  51674. /**
  51675. * Create a new RuntimeAnimation object
  51676. * @param target defines the target of the animation
  51677. * @param animation defines the source animation object
  51678. * @param scene defines the hosting scene
  51679. * @param host defines the initiating Animatable
  51680. */
  51681. function RuntimeAnimation(target, animation, scene, host) {
  51682. var _this = this;
  51683. this._events = new Array();
  51684. /**
  51685. * The current frame of the runtime animation
  51686. */
  51687. this._currentFrame = 0;
  51688. /**
  51689. * The original value of the runtime animation
  51690. */
  51691. this._originalValue = new Array();
  51692. /**
  51693. * The offsets cache of the runtime animation
  51694. */
  51695. this._offsetsCache = {};
  51696. /**
  51697. * The high limits cache of the runtime animation
  51698. */
  51699. this._highLimitsCache = {};
  51700. /**
  51701. * Specifies if the runtime animation has been stopped
  51702. */
  51703. this._stopped = false;
  51704. /**
  51705. * The blending factor of the runtime animation
  51706. */
  51707. this._blendingFactor = 0;
  51708. /**
  51709. * The target path of the runtime animation
  51710. */
  51711. this._targetPath = "";
  51712. /**
  51713. * The weight of the runtime animation
  51714. */
  51715. this._weight = 1.0;
  51716. /**
  51717. * The ratio offset of the runtime animation
  51718. */
  51719. this._ratioOffset = 0;
  51720. /**
  51721. * The previous delay of the runtime animation
  51722. */
  51723. this._previousDelay = 0;
  51724. /**
  51725. * The previous ratio of the runtime animation
  51726. */
  51727. this._previousRatio = 0;
  51728. this._animation = animation;
  51729. this._target = target;
  51730. this._scene = scene;
  51731. this._host = host;
  51732. animation._runtimeAnimations.push(this);
  51733. // Cloning events locally
  51734. var events = animation.getEvents();
  51735. if (events && events.length > 0) {
  51736. events.forEach(function (e) {
  51737. _this._events.push(e._clone());
  51738. });
  51739. }
  51740. }
  51741. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51742. /**
  51743. * Gets the current frame of the runtime animation
  51744. */
  51745. get: function () {
  51746. return this._currentFrame;
  51747. },
  51748. enumerable: true,
  51749. configurable: true
  51750. });
  51751. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51752. /**
  51753. * Gets the weight of the runtime animation
  51754. */
  51755. get: function () {
  51756. return this._weight;
  51757. },
  51758. enumerable: true,
  51759. configurable: true
  51760. });
  51761. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51762. /**
  51763. * Gets the current value of the runtime animation
  51764. */
  51765. get: function () {
  51766. return this._currentValue;
  51767. },
  51768. enumerable: true,
  51769. configurable: true
  51770. });
  51771. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51772. /**
  51773. * Gets the target path of the runtime animation
  51774. */
  51775. get: function () {
  51776. return this._targetPath;
  51777. },
  51778. enumerable: true,
  51779. configurable: true
  51780. });
  51781. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51782. /**
  51783. * Gets the actual target of the runtime animation
  51784. */
  51785. get: function () {
  51786. return this._activeTarget;
  51787. },
  51788. enumerable: true,
  51789. configurable: true
  51790. });
  51791. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51792. /**
  51793. * Gets the animation from the runtime animation
  51794. */
  51795. get: function () {
  51796. return this._animation;
  51797. },
  51798. enumerable: true,
  51799. configurable: true
  51800. });
  51801. /**
  51802. * Resets the runtime animation to the beginning
  51803. * @param restoreOriginal defines whether to restore the target property to the original value
  51804. */
  51805. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51806. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51807. if (restoreOriginal) {
  51808. if (this._target instanceof Array) {
  51809. var index = 0;
  51810. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51811. var target = _a[_i];
  51812. if (this._originalValue[index] !== undefined) {
  51813. this._setValue(target, this._originalValue[index], -1);
  51814. }
  51815. index++;
  51816. }
  51817. }
  51818. else {
  51819. if (this._originalValue[0] !== undefined) {
  51820. this._setValue(this._target, this._originalValue[0], -1);
  51821. }
  51822. }
  51823. }
  51824. this._offsetsCache = {};
  51825. this._highLimitsCache = {};
  51826. this._currentFrame = 0;
  51827. this._blendingFactor = 0;
  51828. this._originalValue = new Array();
  51829. // Events
  51830. for (var index = 0; index < this._events.length; index++) {
  51831. this._events[index].isDone = false;
  51832. }
  51833. };
  51834. /**
  51835. * Specifies if the runtime animation is stopped
  51836. * @returns Boolean specifying if the runtime animation is stopped
  51837. */
  51838. RuntimeAnimation.prototype.isStopped = function () {
  51839. return this._stopped;
  51840. };
  51841. /**
  51842. * Disposes of the runtime animation
  51843. */
  51844. RuntimeAnimation.prototype.dispose = function () {
  51845. var index = this._animation.runtimeAnimations.indexOf(this);
  51846. if (index > -1) {
  51847. this._animation.runtimeAnimations.splice(index, 1);
  51848. }
  51849. };
  51850. /**
  51851. * Interpolates the animation from the current frame
  51852. * @param currentFrame The frame to interpolate the animation to
  51853. * @param repeatCount The number of times that the animation should loop
  51854. * @param loopMode The type of looping mode to use
  51855. * @param offsetValue Animation offset value
  51856. * @param highLimitValue The high limit value
  51857. * @returns The interpolated value
  51858. */
  51859. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51860. this._currentFrame = currentFrame;
  51861. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51862. this._workValue = BABYLON.Matrix.Zero();
  51863. }
  51864. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51865. };
  51866. /**
  51867. * Apply the interpolated value to the target
  51868. * @param currentValue defines the value computed by the animation
  51869. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51870. */
  51871. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51872. if (weight === void 0) { weight = 1.0; }
  51873. if (this._target instanceof Array) {
  51874. var index = 0;
  51875. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51876. var target = _a[_i];
  51877. this._setValue(target, currentValue, weight, index);
  51878. index++;
  51879. }
  51880. }
  51881. else {
  51882. this._setValue(this._target, currentValue, weight);
  51883. }
  51884. };
  51885. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51886. if (targetIndex === void 0) { targetIndex = 0; }
  51887. // Set value
  51888. var path;
  51889. var destination;
  51890. var targetPropertyPath = this._animation.targetPropertyPath;
  51891. if (targetPropertyPath.length > 1) {
  51892. var property = target[targetPropertyPath[0]];
  51893. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51894. property = property[targetPropertyPath[index]];
  51895. }
  51896. path = targetPropertyPath[targetPropertyPath.length - 1];
  51897. destination = property;
  51898. }
  51899. else {
  51900. path = targetPropertyPath[0];
  51901. destination = target;
  51902. }
  51903. this._targetPath = path;
  51904. this._activeTarget = destination;
  51905. this._weight = weight;
  51906. if (this._originalValue[targetIndex] === undefined) {
  51907. var originalValue = void 0;
  51908. if (destination.getRestPose && path === "_matrix") { // For bones
  51909. originalValue = destination.getRestPose();
  51910. }
  51911. else {
  51912. originalValue = destination[path];
  51913. }
  51914. if (originalValue && originalValue.clone) {
  51915. this._originalValue[targetIndex] = originalValue.clone();
  51916. }
  51917. else {
  51918. this._originalValue[targetIndex] = originalValue;
  51919. }
  51920. }
  51921. // Blending
  51922. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51923. if (enableBlending && this._blendingFactor <= 1.0) {
  51924. if (!this._originalBlendValue) {
  51925. var originalValue = destination[path];
  51926. if (originalValue.clone) {
  51927. this._originalBlendValue = originalValue.clone();
  51928. }
  51929. else {
  51930. this._originalBlendValue = originalValue;
  51931. }
  51932. }
  51933. if (this._originalBlendValue.m) { // Matrix
  51934. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51935. if (this._currentValue) {
  51936. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51937. }
  51938. else {
  51939. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51940. }
  51941. }
  51942. else {
  51943. if (this._currentValue) {
  51944. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51945. }
  51946. else {
  51947. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51948. }
  51949. }
  51950. }
  51951. else {
  51952. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51953. }
  51954. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51955. this._blendingFactor += blendingSpeed;
  51956. }
  51957. else {
  51958. this._currentValue = currentValue;
  51959. }
  51960. if (weight !== -1.0) {
  51961. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51962. }
  51963. else {
  51964. destination[path] = this._currentValue;
  51965. }
  51966. if (target.markAsDirty) {
  51967. target.markAsDirty(this._animation.targetProperty);
  51968. }
  51969. };
  51970. /**
  51971. * Gets the loop pmode of the runtime animation
  51972. * @returns Loop Mode
  51973. */
  51974. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51975. if (this._target && this._target.animationPropertiesOverride) {
  51976. return this._target.animationPropertiesOverride.loopMode;
  51977. }
  51978. return this._animation.loopMode;
  51979. };
  51980. /**
  51981. * Move the current animation to a given frame
  51982. * @param frame defines the frame to move to
  51983. */
  51984. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51985. var keys = this._animation.getKeys();
  51986. if (frame < keys[0].frame) {
  51987. frame = keys[0].frame;
  51988. }
  51989. else if (frame > keys[keys.length - 1].frame) {
  51990. frame = keys[keys.length - 1].frame;
  51991. }
  51992. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51993. this.setValue(currentValue, -1);
  51994. };
  51995. /**
  51996. * @hidden Internal use only
  51997. */
  51998. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51999. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52000. this._ratioOffset = this._previousRatio - newRatio;
  52001. };
  52002. /**
  52003. * Execute the current animation
  52004. * @param delay defines the delay to add to the current frame
  52005. * @param from defines the lower bound of the animation range
  52006. * @param to defines the upper bound of the animation range
  52007. * @param loop defines if the current animation must loop
  52008. * @param speedRatio defines the current speed ratio
  52009. * @param weight defines the weight of the animation (default is -1 so no weight)
  52010. * @returns a boolean indicating if the animation has ended
  52011. */
  52012. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52013. if (weight === void 0) { weight = -1.0; }
  52014. var targetPropertyPath = this._animation.targetPropertyPath;
  52015. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52016. this._stopped = true;
  52017. return false;
  52018. }
  52019. var returnValue = true;
  52020. var keys = this._animation.getKeys();
  52021. // Adding a start key at frame 0 if missing
  52022. if (keys[0].frame !== 0) {
  52023. var newKey = { frame: 0, value: keys[0].value };
  52024. keys.splice(0, 0, newKey);
  52025. }
  52026. // Check limits
  52027. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52028. from = keys[0].frame;
  52029. }
  52030. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52031. to = keys[keys.length - 1].frame;
  52032. }
  52033. //to and from cannot be the same key
  52034. if (from === to) {
  52035. if (from > keys[0].frame) {
  52036. from--;
  52037. }
  52038. else if (to < keys[keys.length - 1].frame) {
  52039. to++;
  52040. }
  52041. }
  52042. // Compute ratio
  52043. var range = to - from;
  52044. var offsetValue;
  52045. // ratio represents the frame delta between from and to
  52046. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52047. var highLimitValue = 0;
  52048. this._previousDelay = delay;
  52049. this._previousRatio = ratio;
  52050. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52051. returnValue = false;
  52052. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52053. }
  52054. else {
  52055. // Get max value if required
  52056. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52057. var keyOffset = to.toString() + from.toString();
  52058. if (!this._offsetsCache[keyOffset]) {
  52059. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52060. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52061. switch (this._animation.dataType) {
  52062. // Float
  52063. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52064. this._offsetsCache[keyOffset] = toValue - fromValue;
  52065. break;
  52066. // Quaternion
  52067. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52068. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52069. break;
  52070. // Vector3
  52071. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52072. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52073. // Vector2
  52074. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52075. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52076. // Size
  52077. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52078. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52079. // Color3
  52080. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52081. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52082. default:
  52083. break;
  52084. }
  52085. this._highLimitsCache[keyOffset] = toValue;
  52086. }
  52087. highLimitValue = this._highLimitsCache[keyOffset];
  52088. offsetValue = this._offsetsCache[keyOffset];
  52089. }
  52090. }
  52091. if (offsetValue === undefined) {
  52092. switch (this._animation.dataType) {
  52093. // Float
  52094. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52095. offsetValue = 0;
  52096. break;
  52097. // Quaternion
  52098. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52099. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52100. break;
  52101. // Vector3
  52102. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52103. offsetValue = BABYLON.Vector3.Zero();
  52104. break;
  52105. // Vector2
  52106. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52107. offsetValue = BABYLON.Vector2.Zero();
  52108. break;
  52109. // Size
  52110. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52111. offsetValue = BABYLON.Size.Zero();
  52112. break;
  52113. // Color3
  52114. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52115. offsetValue = BABYLON.Color3.Black();
  52116. }
  52117. }
  52118. // Compute value
  52119. var repeatCount = (ratio / range) >> 0;
  52120. var currentFrame = returnValue ? from + ratio % range : to;
  52121. // Need to normalize?
  52122. if (this._host && this._host.syncRoot) {
  52123. var syncRoot = this._host.syncRoot;
  52124. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52125. currentFrame = from + (to - from) * hostNormalizedFrame;
  52126. }
  52127. // Reset events if looping
  52128. var events = this._events;
  52129. if (range > 0 && this.currentFrame > currentFrame ||
  52130. range < 0 && this.currentFrame < currentFrame) {
  52131. // Need to reset animation events
  52132. for (var index = 0; index < events.length; index++) {
  52133. if (!events[index].onlyOnce) {
  52134. // reset event, the animation is looping
  52135. events[index].isDone = false;
  52136. }
  52137. }
  52138. }
  52139. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52140. // Set value
  52141. this.setValue(currentValue, weight);
  52142. // Check events
  52143. for (var index = 0; index < events.length; index++) {
  52144. // Make sure current frame has passed event frame and that event frame is within the current range
  52145. // Also, handle both forward and reverse animations
  52146. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52147. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52148. var event = events[index];
  52149. if (!event.isDone) {
  52150. // If event should be done only once, remove it.
  52151. if (event.onlyOnce) {
  52152. events.splice(index, 1);
  52153. index--;
  52154. }
  52155. event.isDone = true;
  52156. event.action();
  52157. } // Don't do anything if the event has already be done.
  52158. }
  52159. }
  52160. if (!returnValue) {
  52161. this._stopped = true;
  52162. }
  52163. return returnValue;
  52164. };
  52165. return RuntimeAnimation;
  52166. }());
  52167. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52168. })(BABYLON || (BABYLON = {}));
  52169. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52170. var BABYLON;
  52171. (function (BABYLON) {
  52172. var Animatable = /** @class */ (function () {
  52173. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52174. if (fromFrame === void 0) { fromFrame = 0; }
  52175. if (toFrame === void 0) { toFrame = 100; }
  52176. if (loopAnimation === void 0) { loopAnimation = false; }
  52177. if (speedRatio === void 0) { speedRatio = 1.0; }
  52178. this.target = target;
  52179. this.fromFrame = fromFrame;
  52180. this.toFrame = toFrame;
  52181. this.loopAnimation = loopAnimation;
  52182. this.onAnimationEnd = onAnimationEnd;
  52183. this._localDelayOffset = null;
  52184. this._pausedDelay = null;
  52185. this._runtimeAnimations = new Array();
  52186. this._paused = false;
  52187. this._speedRatio = 1;
  52188. this._weight = -1.0;
  52189. this.animationStarted = false;
  52190. this._scene = scene;
  52191. if (animations) {
  52192. this.appendAnimations(target, animations);
  52193. }
  52194. this._speedRatio = speedRatio;
  52195. scene._activeAnimatables.push(this);
  52196. }
  52197. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52198. /**
  52199. * Gets the root Animatable used to synchronize and normalize animations
  52200. */
  52201. get: function () {
  52202. return this._syncRoot;
  52203. },
  52204. enumerable: true,
  52205. configurable: true
  52206. });
  52207. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52208. /**
  52209. * Gets the current frame of the first RuntimeAnimation
  52210. * Used to synchronize Animatables
  52211. */
  52212. get: function () {
  52213. if (this._runtimeAnimations.length === 0) {
  52214. return 0;
  52215. }
  52216. return this._runtimeAnimations[0].currentFrame;
  52217. },
  52218. enumerable: true,
  52219. configurable: true
  52220. });
  52221. Object.defineProperty(Animatable.prototype, "weight", {
  52222. /**
  52223. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52224. */
  52225. get: function () {
  52226. return this._weight;
  52227. },
  52228. set: function (value) {
  52229. if (value === -1) { // -1 is ok and means no weight
  52230. this._weight = -1;
  52231. return;
  52232. }
  52233. // Else weight must be in [0, 1] range
  52234. this._weight = Math.min(Math.max(value, 0), 1.0);
  52235. },
  52236. enumerable: true,
  52237. configurable: true
  52238. });
  52239. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52240. /**
  52241. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52242. */
  52243. get: function () {
  52244. return this._speedRatio;
  52245. },
  52246. set: function (value) {
  52247. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52248. var animation = this._runtimeAnimations[index];
  52249. animation._prepareForSpeedRatioChange(value);
  52250. }
  52251. this._speedRatio = value;
  52252. },
  52253. enumerable: true,
  52254. configurable: true
  52255. });
  52256. // Methods
  52257. /**
  52258. * Synchronize and normalize current Animatable with a source Animatable
  52259. * This is useful when using animation weights and when animations are not of the same length
  52260. * @param root defines the root Animatable to synchronize with
  52261. * @returns the current Animatable
  52262. */
  52263. Animatable.prototype.syncWith = function (root) {
  52264. this._syncRoot = root;
  52265. if (root) {
  52266. // Make sure this animatable will animate after the root
  52267. var index = this._scene._activeAnimatables.indexOf(this);
  52268. if (index > -1) {
  52269. this._scene._activeAnimatables.splice(index, 1);
  52270. this._scene._activeAnimatables.push(this);
  52271. }
  52272. }
  52273. return this;
  52274. };
  52275. Animatable.prototype.getAnimations = function () {
  52276. return this._runtimeAnimations;
  52277. };
  52278. Animatable.prototype.appendAnimations = function (target, animations) {
  52279. for (var index = 0; index < animations.length; index++) {
  52280. var animation = animations[index];
  52281. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52282. }
  52283. };
  52284. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52285. var runtimeAnimations = this._runtimeAnimations;
  52286. for (var index = 0; index < runtimeAnimations.length; index++) {
  52287. if (runtimeAnimations[index].animation.targetProperty === property) {
  52288. return runtimeAnimations[index].animation;
  52289. }
  52290. }
  52291. return null;
  52292. };
  52293. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52294. var runtimeAnimations = this._runtimeAnimations;
  52295. for (var index = 0; index < runtimeAnimations.length; index++) {
  52296. if (runtimeAnimations[index].animation.targetProperty === property) {
  52297. return runtimeAnimations[index];
  52298. }
  52299. }
  52300. return null;
  52301. };
  52302. Animatable.prototype.reset = function () {
  52303. var runtimeAnimations = this._runtimeAnimations;
  52304. for (var index = 0; index < runtimeAnimations.length; index++) {
  52305. runtimeAnimations[index].reset(true);
  52306. }
  52307. this._localDelayOffset = null;
  52308. this._pausedDelay = null;
  52309. };
  52310. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52311. var runtimeAnimations = this._runtimeAnimations;
  52312. for (var index = 0; index < runtimeAnimations.length; index++) {
  52313. runtimeAnimations[index].animation.enableBlending = true;
  52314. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52315. }
  52316. };
  52317. Animatable.prototype.disableBlending = function () {
  52318. var runtimeAnimations = this._runtimeAnimations;
  52319. for (var index = 0; index < runtimeAnimations.length; index++) {
  52320. runtimeAnimations[index].animation.enableBlending = false;
  52321. }
  52322. };
  52323. Animatable.prototype.goToFrame = function (frame) {
  52324. var runtimeAnimations = this._runtimeAnimations;
  52325. if (runtimeAnimations[0]) {
  52326. var fps = runtimeAnimations[0].animation.framePerSecond;
  52327. var currentFrame = runtimeAnimations[0].currentFrame;
  52328. var adjustTime = frame - currentFrame;
  52329. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52330. if (this._localDelayOffset === null) {
  52331. this._localDelayOffset = 0;
  52332. }
  52333. this._localDelayOffset -= delay;
  52334. }
  52335. for (var index = 0; index < runtimeAnimations.length; index++) {
  52336. runtimeAnimations[index].goToFrame(frame);
  52337. }
  52338. };
  52339. Animatable.prototype.pause = function () {
  52340. if (this._paused) {
  52341. return;
  52342. }
  52343. this._paused = true;
  52344. };
  52345. Animatable.prototype.restart = function () {
  52346. this._paused = false;
  52347. };
  52348. Animatable.prototype.stop = function (animationName) {
  52349. if (animationName) {
  52350. var idx = this._scene._activeAnimatables.indexOf(this);
  52351. if (idx > -1) {
  52352. var runtimeAnimations = this._runtimeAnimations;
  52353. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52354. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52355. continue;
  52356. }
  52357. runtimeAnimations[index].dispose();
  52358. runtimeAnimations.splice(index, 1);
  52359. }
  52360. if (runtimeAnimations.length == 0) {
  52361. this._scene._activeAnimatables.splice(idx, 1);
  52362. if (this.onAnimationEnd) {
  52363. this.onAnimationEnd();
  52364. }
  52365. }
  52366. }
  52367. }
  52368. else {
  52369. var index = this._scene._activeAnimatables.indexOf(this);
  52370. if (index > -1) {
  52371. this._scene._activeAnimatables.splice(index, 1);
  52372. var runtimeAnimations = this._runtimeAnimations;
  52373. for (var index = 0; index < runtimeAnimations.length; index++) {
  52374. runtimeAnimations[index].dispose();
  52375. }
  52376. if (this.onAnimationEnd) {
  52377. this.onAnimationEnd();
  52378. }
  52379. }
  52380. }
  52381. };
  52382. Animatable.prototype._animate = function (delay) {
  52383. if (this._paused) {
  52384. this.animationStarted = false;
  52385. if (this._pausedDelay === null) {
  52386. this._pausedDelay = delay;
  52387. }
  52388. return true;
  52389. }
  52390. if (this._localDelayOffset === null) {
  52391. this._localDelayOffset = delay;
  52392. this._pausedDelay = null;
  52393. }
  52394. else if (this._pausedDelay !== null) {
  52395. this._localDelayOffset += delay - this._pausedDelay;
  52396. this._pausedDelay = null;
  52397. }
  52398. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52399. return true;
  52400. }
  52401. // Animating
  52402. var running = false;
  52403. var runtimeAnimations = this._runtimeAnimations;
  52404. var index;
  52405. for (index = 0; index < runtimeAnimations.length; index++) {
  52406. var animation = runtimeAnimations[index];
  52407. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52408. running = running || isRunning;
  52409. }
  52410. this.animationStarted = running;
  52411. if (!running) {
  52412. // Remove from active animatables
  52413. index = this._scene._activeAnimatables.indexOf(this);
  52414. this._scene._activeAnimatables.splice(index, 1);
  52415. // Dispose all runtime animations
  52416. for (index = 0; index < runtimeAnimations.length; index++) {
  52417. runtimeAnimations[index].dispose();
  52418. }
  52419. }
  52420. if (!running && this.onAnimationEnd) {
  52421. this.onAnimationEnd();
  52422. this.onAnimationEnd = null;
  52423. }
  52424. return running;
  52425. };
  52426. return Animatable;
  52427. }());
  52428. BABYLON.Animatable = Animatable;
  52429. })(BABYLON || (BABYLON = {}));
  52430. //# sourceMappingURL=babylon.animatable.js.map
  52431. var BABYLON;
  52432. (function (BABYLON) {
  52433. var EasingFunction = /** @class */ (function () {
  52434. function EasingFunction() {
  52435. // Properties
  52436. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52437. }
  52438. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52439. get: function () {
  52440. return EasingFunction._EASINGMODE_EASEIN;
  52441. },
  52442. enumerable: true,
  52443. configurable: true
  52444. });
  52445. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52446. get: function () {
  52447. return EasingFunction._EASINGMODE_EASEOUT;
  52448. },
  52449. enumerable: true,
  52450. configurable: true
  52451. });
  52452. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52453. get: function () {
  52454. return EasingFunction._EASINGMODE_EASEINOUT;
  52455. },
  52456. enumerable: true,
  52457. configurable: true
  52458. });
  52459. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52460. var n = Math.min(Math.max(easingMode, 0), 2);
  52461. this._easingMode = n;
  52462. };
  52463. EasingFunction.prototype.getEasingMode = function () {
  52464. return this._easingMode;
  52465. };
  52466. EasingFunction.prototype.easeInCore = function (gradient) {
  52467. throw new Error('You must implement this method');
  52468. };
  52469. EasingFunction.prototype.ease = function (gradient) {
  52470. switch (this._easingMode) {
  52471. case EasingFunction.EASINGMODE_EASEIN:
  52472. return this.easeInCore(gradient);
  52473. case EasingFunction.EASINGMODE_EASEOUT:
  52474. return (1 - this.easeInCore(1 - gradient));
  52475. }
  52476. if (gradient >= 0.5) {
  52477. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52478. }
  52479. return (this.easeInCore(gradient * 2) * 0.5);
  52480. };
  52481. //Statics
  52482. EasingFunction._EASINGMODE_EASEIN = 0;
  52483. EasingFunction._EASINGMODE_EASEOUT = 1;
  52484. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52485. return EasingFunction;
  52486. }());
  52487. BABYLON.EasingFunction = EasingFunction;
  52488. var CircleEase = /** @class */ (function (_super) {
  52489. __extends(CircleEase, _super);
  52490. function CircleEase() {
  52491. return _super !== null && _super.apply(this, arguments) || this;
  52492. }
  52493. CircleEase.prototype.easeInCore = function (gradient) {
  52494. gradient = Math.max(0, Math.min(1, gradient));
  52495. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52496. };
  52497. return CircleEase;
  52498. }(EasingFunction));
  52499. BABYLON.CircleEase = CircleEase;
  52500. var BackEase = /** @class */ (function (_super) {
  52501. __extends(BackEase, _super);
  52502. function BackEase(amplitude) {
  52503. if (amplitude === void 0) { amplitude = 1; }
  52504. var _this = _super.call(this) || this;
  52505. _this.amplitude = amplitude;
  52506. return _this;
  52507. }
  52508. BackEase.prototype.easeInCore = function (gradient) {
  52509. var num = Math.max(0, this.amplitude);
  52510. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52511. };
  52512. return BackEase;
  52513. }(EasingFunction));
  52514. BABYLON.BackEase = BackEase;
  52515. var BounceEase = /** @class */ (function (_super) {
  52516. __extends(BounceEase, _super);
  52517. function BounceEase(bounces, bounciness) {
  52518. if (bounces === void 0) { bounces = 3; }
  52519. if (bounciness === void 0) { bounciness = 2; }
  52520. var _this = _super.call(this) || this;
  52521. _this.bounces = bounces;
  52522. _this.bounciness = bounciness;
  52523. return _this;
  52524. }
  52525. BounceEase.prototype.easeInCore = function (gradient) {
  52526. var y = Math.max(0.0, this.bounces);
  52527. var bounciness = this.bounciness;
  52528. if (bounciness <= 1.0) {
  52529. bounciness = 1.001;
  52530. }
  52531. var num9 = Math.pow(bounciness, y);
  52532. var num5 = 1.0 - bounciness;
  52533. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52534. var num15 = gradient * num4;
  52535. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52536. var num3 = Math.floor(num65);
  52537. var num13 = num3 + 1.0;
  52538. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52539. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52540. var num7 = (num8 + num12) * 0.5;
  52541. var num6 = gradient - num7;
  52542. var num2 = num7 - num8;
  52543. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52544. };
  52545. return BounceEase;
  52546. }(EasingFunction));
  52547. BABYLON.BounceEase = BounceEase;
  52548. var CubicEase = /** @class */ (function (_super) {
  52549. __extends(CubicEase, _super);
  52550. function CubicEase() {
  52551. return _super !== null && _super.apply(this, arguments) || this;
  52552. }
  52553. CubicEase.prototype.easeInCore = function (gradient) {
  52554. return (gradient * gradient * gradient);
  52555. };
  52556. return CubicEase;
  52557. }(EasingFunction));
  52558. BABYLON.CubicEase = CubicEase;
  52559. var ElasticEase = /** @class */ (function (_super) {
  52560. __extends(ElasticEase, _super);
  52561. function ElasticEase(oscillations, springiness) {
  52562. if (oscillations === void 0) { oscillations = 3; }
  52563. if (springiness === void 0) { springiness = 3; }
  52564. var _this = _super.call(this) || this;
  52565. _this.oscillations = oscillations;
  52566. _this.springiness = springiness;
  52567. return _this;
  52568. }
  52569. ElasticEase.prototype.easeInCore = function (gradient) {
  52570. var num2;
  52571. var num3 = Math.max(0.0, this.oscillations);
  52572. var num = Math.max(0.0, this.springiness);
  52573. if (num == 0) {
  52574. num2 = gradient;
  52575. }
  52576. else {
  52577. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52578. }
  52579. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52580. };
  52581. return ElasticEase;
  52582. }(EasingFunction));
  52583. BABYLON.ElasticEase = ElasticEase;
  52584. var ExponentialEase = /** @class */ (function (_super) {
  52585. __extends(ExponentialEase, _super);
  52586. function ExponentialEase(exponent) {
  52587. if (exponent === void 0) { exponent = 2; }
  52588. var _this = _super.call(this) || this;
  52589. _this.exponent = exponent;
  52590. return _this;
  52591. }
  52592. ExponentialEase.prototype.easeInCore = function (gradient) {
  52593. if (this.exponent <= 0) {
  52594. return gradient;
  52595. }
  52596. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52597. };
  52598. return ExponentialEase;
  52599. }(EasingFunction));
  52600. BABYLON.ExponentialEase = ExponentialEase;
  52601. var PowerEase = /** @class */ (function (_super) {
  52602. __extends(PowerEase, _super);
  52603. function PowerEase(power) {
  52604. if (power === void 0) { power = 2; }
  52605. var _this = _super.call(this) || this;
  52606. _this.power = power;
  52607. return _this;
  52608. }
  52609. PowerEase.prototype.easeInCore = function (gradient) {
  52610. var y = Math.max(0.0, this.power);
  52611. return Math.pow(gradient, y);
  52612. };
  52613. return PowerEase;
  52614. }(EasingFunction));
  52615. BABYLON.PowerEase = PowerEase;
  52616. var QuadraticEase = /** @class */ (function (_super) {
  52617. __extends(QuadraticEase, _super);
  52618. function QuadraticEase() {
  52619. return _super !== null && _super.apply(this, arguments) || this;
  52620. }
  52621. QuadraticEase.prototype.easeInCore = function (gradient) {
  52622. return (gradient * gradient);
  52623. };
  52624. return QuadraticEase;
  52625. }(EasingFunction));
  52626. BABYLON.QuadraticEase = QuadraticEase;
  52627. var QuarticEase = /** @class */ (function (_super) {
  52628. __extends(QuarticEase, _super);
  52629. function QuarticEase() {
  52630. return _super !== null && _super.apply(this, arguments) || this;
  52631. }
  52632. QuarticEase.prototype.easeInCore = function (gradient) {
  52633. return (gradient * gradient * gradient * gradient);
  52634. };
  52635. return QuarticEase;
  52636. }(EasingFunction));
  52637. BABYLON.QuarticEase = QuarticEase;
  52638. var QuinticEase = /** @class */ (function (_super) {
  52639. __extends(QuinticEase, _super);
  52640. function QuinticEase() {
  52641. return _super !== null && _super.apply(this, arguments) || this;
  52642. }
  52643. QuinticEase.prototype.easeInCore = function (gradient) {
  52644. return (gradient * gradient * gradient * gradient * gradient);
  52645. };
  52646. return QuinticEase;
  52647. }(EasingFunction));
  52648. BABYLON.QuinticEase = QuinticEase;
  52649. var SineEase = /** @class */ (function (_super) {
  52650. __extends(SineEase, _super);
  52651. function SineEase() {
  52652. return _super !== null && _super.apply(this, arguments) || this;
  52653. }
  52654. SineEase.prototype.easeInCore = function (gradient) {
  52655. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52656. };
  52657. return SineEase;
  52658. }(EasingFunction));
  52659. BABYLON.SineEase = SineEase;
  52660. var BezierCurveEase = /** @class */ (function (_super) {
  52661. __extends(BezierCurveEase, _super);
  52662. function BezierCurveEase(x1, y1, x2, y2) {
  52663. if (x1 === void 0) { x1 = 0; }
  52664. if (y1 === void 0) { y1 = 0; }
  52665. if (x2 === void 0) { x2 = 1; }
  52666. if (y2 === void 0) { y2 = 1; }
  52667. var _this = _super.call(this) || this;
  52668. _this.x1 = x1;
  52669. _this.y1 = y1;
  52670. _this.x2 = x2;
  52671. _this.y2 = y2;
  52672. return _this;
  52673. }
  52674. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52675. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52676. };
  52677. return BezierCurveEase;
  52678. }(EasingFunction));
  52679. BABYLON.BezierCurveEase = BezierCurveEase;
  52680. })(BABYLON || (BABYLON = {}));
  52681. //# sourceMappingURL=babylon.easing.js.map
  52682. var BABYLON;
  52683. (function (BABYLON) {
  52684. /**
  52685. * A Condition applied to an Action
  52686. */
  52687. var Condition = /** @class */ (function () {
  52688. /**
  52689. * Creates a new Condition
  52690. * @param actionManager the manager of the action the condition is applied to
  52691. */
  52692. function Condition(actionManager) {
  52693. this._actionManager = actionManager;
  52694. }
  52695. /**
  52696. * Check if the current condition is valid
  52697. * @returns a boolean
  52698. */
  52699. Condition.prototype.isValid = function () {
  52700. return true;
  52701. };
  52702. /**
  52703. * Internal only
  52704. * @hidden
  52705. */
  52706. Condition.prototype._getProperty = function (propertyPath) {
  52707. return this._actionManager._getProperty(propertyPath);
  52708. };
  52709. /**
  52710. * Internal only
  52711. * @hidden
  52712. */
  52713. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52714. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52715. };
  52716. /**
  52717. * Serialize placeholder for child classes
  52718. * @returns the serialized object
  52719. */
  52720. Condition.prototype.serialize = function () {
  52721. };
  52722. /**
  52723. * Internal only
  52724. * @hidden
  52725. */
  52726. Condition.prototype._serialize = function (serializedCondition) {
  52727. return {
  52728. type: 2,
  52729. children: [],
  52730. name: serializedCondition.name,
  52731. properties: serializedCondition.properties
  52732. };
  52733. };
  52734. return Condition;
  52735. }());
  52736. BABYLON.Condition = Condition;
  52737. /**
  52738. * Defines specific conditional operators as extensions of Condition
  52739. */
  52740. var ValueCondition = /** @class */ (function (_super) {
  52741. __extends(ValueCondition, _super);
  52742. /**
  52743. * Creates a new ValueCondition
  52744. * @param actionManager manager for the action the condition applies to
  52745. * @param target for the action
  52746. * @param propertyPath path to specify the property of the target the conditional operator uses
  52747. * @param value the value compared by the conditional operator against the current value of the property
  52748. * @param operator the conditional operator, default ValueCondition.IsEqual
  52749. */
  52750. function ValueCondition(actionManager, target,
  52751. /** path to specify the property of the target the conditional operator uses */
  52752. propertyPath,
  52753. /** the value compared by the conditional operator against the current value of the property */
  52754. value,
  52755. /** the conditional operator, default ValueCondition.IsEqual */
  52756. operator) {
  52757. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52758. var _this = _super.call(this, actionManager) || this;
  52759. _this.propertyPath = propertyPath;
  52760. _this.value = value;
  52761. _this.operator = operator;
  52762. _this._target = target;
  52763. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52764. _this._property = _this._getProperty(_this.propertyPath);
  52765. return _this;
  52766. }
  52767. Object.defineProperty(ValueCondition, "IsEqual", {
  52768. /**
  52769. * returns the number for IsEqual
  52770. */
  52771. get: function () {
  52772. return ValueCondition._IsEqual;
  52773. },
  52774. enumerable: true,
  52775. configurable: true
  52776. });
  52777. Object.defineProperty(ValueCondition, "IsDifferent", {
  52778. /**
  52779. * Returns the number for IsDifferent
  52780. */
  52781. get: function () {
  52782. return ValueCondition._IsDifferent;
  52783. },
  52784. enumerable: true,
  52785. configurable: true
  52786. });
  52787. Object.defineProperty(ValueCondition, "IsGreater", {
  52788. /**
  52789. * Returns the number for IsGreater
  52790. */
  52791. get: function () {
  52792. return ValueCondition._IsGreater;
  52793. },
  52794. enumerable: true,
  52795. configurable: true
  52796. });
  52797. Object.defineProperty(ValueCondition, "IsLesser", {
  52798. /**
  52799. * Returns the number for IsLesser
  52800. */
  52801. get: function () {
  52802. return ValueCondition._IsLesser;
  52803. },
  52804. enumerable: true,
  52805. configurable: true
  52806. });
  52807. /**
  52808. * Compares the given value with the property value for the specified conditional operator
  52809. * @returns the result of the comparison
  52810. */
  52811. ValueCondition.prototype.isValid = function () {
  52812. switch (this.operator) {
  52813. case ValueCondition.IsGreater:
  52814. return this._effectiveTarget[this._property] > this.value;
  52815. case ValueCondition.IsLesser:
  52816. return this._effectiveTarget[this._property] < this.value;
  52817. case ValueCondition.IsEqual:
  52818. case ValueCondition.IsDifferent:
  52819. var check;
  52820. if (this.value.equals) {
  52821. check = this.value.equals(this._effectiveTarget[this._property]);
  52822. }
  52823. else {
  52824. check = this.value === this._effectiveTarget[this._property];
  52825. }
  52826. return this.operator === ValueCondition.IsEqual ? check : !check;
  52827. }
  52828. return false;
  52829. };
  52830. /**
  52831. * Serialize the ValueCondition into a JSON compatible object
  52832. * @returns serialization object
  52833. */
  52834. ValueCondition.prototype.serialize = function () {
  52835. return this._serialize({
  52836. name: "ValueCondition",
  52837. properties: [
  52838. BABYLON.Action._GetTargetProperty(this._target),
  52839. { name: "propertyPath", value: this.propertyPath },
  52840. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52841. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52842. ]
  52843. });
  52844. };
  52845. /**
  52846. * Gets the name of the conditional operator for the ValueCondition
  52847. * @param operator the conditional operator
  52848. * @returns the name
  52849. */
  52850. ValueCondition.GetOperatorName = function (operator) {
  52851. switch (operator) {
  52852. case ValueCondition._IsEqual: return "IsEqual";
  52853. case ValueCondition._IsDifferent: return "IsDifferent";
  52854. case ValueCondition._IsGreater: return "IsGreater";
  52855. case ValueCondition._IsLesser: return "IsLesser";
  52856. default: return "";
  52857. }
  52858. };
  52859. /**
  52860. * Internal only
  52861. * @hidden
  52862. */
  52863. ValueCondition._IsEqual = 0;
  52864. /**
  52865. * Internal only
  52866. * @hidden
  52867. */
  52868. ValueCondition._IsDifferent = 1;
  52869. /**
  52870. * Internal only
  52871. * @hidden
  52872. */
  52873. ValueCondition._IsGreater = 2;
  52874. /**
  52875. * Internal only
  52876. * @hidden
  52877. */
  52878. ValueCondition._IsLesser = 3;
  52879. return ValueCondition;
  52880. }(Condition));
  52881. BABYLON.ValueCondition = ValueCondition;
  52882. /**
  52883. * Defines a predicate condition as an extension of Condition
  52884. */
  52885. var PredicateCondition = /** @class */ (function (_super) {
  52886. __extends(PredicateCondition, _super);
  52887. /**
  52888. * Creates a new PredicateCondition
  52889. * @param actionManager manager for the action the condition applies to
  52890. * @param predicate defines the predicate function used to validate the condition
  52891. */
  52892. function PredicateCondition(actionManager,
  52893. /** defines the predicate function used to validate the condition */
  52894. predicate) {
  52895. var _this = _super.call(this, actionManager) || this;
  52896. _this.predicate = predicate;
  52897. return _this;
  52898. }
  52899. /**
  52900. * @returns the validity of the predicate condition
  52901. */
  52902. PredicateCondition.prototype.isValid = function () {
  52903. return this.predicate();
  52904. };
  52905. return PredicateCondition;
  52906. }(Condition));
  52907. BABYLON.PredicateCondition = PredicateCondition;
  52908. /**
  52909. * Defines a state condition as an extension of Condition
  52910. */
  52911. var StateCondition = /** @class */ (function (_super) {
  52912. __extends(StateCondition, _super);
  52913. /**
  52914. * Creates a new StateCondition
  52915. * @param actionManager manager for the action the condition applies to
  52916. * @param target of the condition
  52917. * @param value to compare with target state
  52918. */
  52919. function StateCondition(actionManager, target, value) {
  52920. var _this = _super.call(this, actionManager) || this;
  52921. _this.value = value;
  52922. _this._target = target;
  52923. return _this;
  52924. }
  52925. /**
  52926. * @returns the validity of the state
  52927. */
  52928. StateCondition.prototype.isValid = function () {
  52929. return this._target.state === this.value;
  52930. };
  52931. /**
  52932. * Serialize the StateCondition into a JSON compatible object
  52933. * @returns serialization object
  52934. */
  52935. StateCondition.prototype.serialize = function () {
  52936. return this._serialize({
  52937. name: "StateCondition",
  52938. properties: [
  52939. BABYLON.Action._GetTargetProperty(this._target),
  52940. { name: "value", value: this.value }
  52941. ]
  52942. });
  52943. };
  52944. return StateCondition;
  52945. }(Condition));
  52946. BABYLON.StateCondition = StateCondition;
  52947. })(BABYLON || (BABYLON = {}));
  52948. //# sourceMappingURL=babylon.condition.js.map
  52949. var BABYLON;
  52950. (function (BABYLON) {
  52951. /**
  52952. * The action to be carried out following a trigger
  52953. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52954. */
  52955. var Action = /** @class */ (function () {
  52956. /**
  52957. * Creates a new Action
  52958. * @param triggerOptions the trigger, with or without parameters, for the action
  52959. * @param condition an optional determinant of action
  52960. */
  52961. function Action(
  52962. /** the trigger, with or without parameters, for the action */
  52963. triggerOptions, condition) {
  52964. this.triggerOptions = triggerOptions;
  52965. /**
  52966. * An event triggered prior to action being executed.
  52967. */
  52968. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52969. if (triggerOptions.parameter) {
  52970. this.trigger = triggerOptions.trigger;
  52971. this._triggerParameter = triggerOptions.parameter;
  52972. }
  52973. else {
  52974. this.trigger = triggerOptions;
  52975. }
  52976. this._nextActiveAction = this;
  52977. this._condition = condition;
  52978. }
  52979. /**
  52980. * Internal only
  52981. * @hidden
  52982. */
  52983. Action.prototype._prepare = function () {
  52984. };
  52985. /**
  52986. * Gets the trigger parameters
  52987. * @returns the trigger parameters
  52988. */
  52989. Action.prototype.getTriggerParameter = function () {
  52990. return this._triggerParameter;
  52991. };
  52992. /**
  52993. * Internal only - executes current action event
  52994. * @hidden
  52995. */
  52996. Action.prototype._executeCurrent = function (evt) {
  52997. if (this._nextActiveAction._condition) {
  52998. var condition = this._nextActiveAction._condition;
  52999. var currentRenderId = this._actionManager.getScene().getRenderId();
  53000. // We cache the current evaluation for the current frame
  53001. if (condition._evaluationId === currentRenderId) {
  53002. if (!condition._currentResult) {
  53003. return;
  53004. }
  53005. }
  53006. else {
  53007. condition._evaluationId = currentRenderId;
  53008. if (!condition.isValid()) {
  53009. condition._currentResult = false;
  53010. return;
  53011. }
  53012. condition._currentResult = true;
  53013. }
  53014. }
  53015. this.onBeforeExecuteObservable.notifyObservers(this);
  53016. this._nextActiveAction.execute(evt);
  53017. this.skipToNextActiveAction();
  53018. };
  53019. /**
  53020. * Execute placeholder for child classes
  53021. * @param evt optional action event
  53022. */
  53023. Action.prototype.execute = function (evt) {
  53024. };
  53025. /**
  53026. * Skips to next active action
  53027. */
  53028. Action.prototype.skipToNextActiveAction = function () {
  53029. if (this._nextActiveAction._child) {
  53030. if (!this._nextActiveAction._child._actionManager) {
  53031. this._nextActiveAction._child._actionManager = this._actionManager;
  53032. }
  53033. this._nextActiveAction = this._nextActiveAction._child;
  53034. }
  53035. else {
  53036. this._nextActiveAction = this;
  53037. }
  53038. };
  53039. /**
  53040. * Adds action to chain of actions, may be a DoNothingAction
  53041. * @param action defines the next action to execute
  53042. * @returns The action passed in
  53043. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53044. */
  53045. Action.prototype.then = function (action) {
  53046. this._child = action;
  53047. action._actionManager = this._actionManager;
  53048. action._prepare();
  53049. return action;
  53050. };
  53051. /**
  53052. * Internal only
  53053. * @hidden
  53054. */
  53055. Action.prototype._getProperty = function (propertyPath) {
  53056. return this._actionManager._getProperty(propertyPath);
  53057. };
  53058. /**
  53059. * Internal only
  53060. * @hidden
  53061. */
  53062. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53063. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53064. };
  53065. /**
  53066. * Serialize placeholder for child classes
  53067. * @param parent of child
  53068. * @returns the serialized object
  53069. */
  53070. Action.prototype.serialize = function (parent) {
  53071. };
  53072. /**
  53073. * Internal only called by serialize
  53074. * @hidden
  53075. */
  53076. Action.prototype._serialize = function (serializedAction, parent) {
  53077. var serializationObject = {
  53078. type: 1,
  53079. children: [],
  53080. name: serializedAction.name,
  53081. properties: serializedAction.properties || []
  53082. };
  53083. // Serialize child
  53084. if (this._child) {
  53085. this._child.serialize(serializationObject);
  53086. }
  53087. // Check if "this" has a condition
  53088. if (this._condition) {
  53089. var serializedCondition = this._condition.serialize();
  53090. serializedCondition.children.push(serializationObject);
  53091. if (parent) {
  53092. parent.children.push(serializedCondition);
  53093. }
  53094. return serializedCondition;
  53095. }
  53096. if (parent) {
  53097. parent.children.push(serializationObject);
  53098. }
  53099. return serializationObject;
  53100. };
  53101. /**
  53102. * Internal only
  53103. * @hidden
  53104. */
  53105. Action._SerializeValueAsString = function (value) {
  53106. if (typeof value === "number") {
  53107. return value.toString();
  53108. }
  53109. if (typeof value === "boolean") {
  53110. return value ? "true" : "false";
  53111. }
  53112. if (value instanceof BABYLON.Vector2) {
  53113. return value.x + ", " + value.y;
  53114. }
  53115. if (value instanceof BABYLON.Vector3) {
  53116. return value.x + ", " + value.y + ", " + value.z;
  53117. }
  53118. if (value instanceof BABYLON.Color3) {
  53119. return value.r + ", " + value.g + ", " + value.b;
  53120. }
  53121. if (value instanceof BABYLON.Color4) {
  53122. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53123. }
  53124. return value; // string
  53125. };
  53126. /**
  53127. * Internal only
  53128. * @hidden
  53129. */
  53130. Action._GetTargetProperty = function (target) {
  53131. return {
  53132. name: "target",
  53133. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53134. : target instanceof BABYLON.Light ? "LightProperties"
  53135. : target instanceof BABYLON.Camera ? "CameraProperties"
  53136. : "SceneProperties",
  53137. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53138. };
  53139. };
  53140. return Action;
  53141. }());
  53142. BABYLON.Action = Action;
  53143. })(BABYLON || (BABYLON = {}));
  53144. //# sourceMappingURL=babylon.action.js.map
  53145. var BABYLON;
  53146. (function (BABYLON) {
  53147. /**
  53148. * ActionEvent is the event being sent when an action is triggered.
  53149. */
  53150. var ActionEvent = /** @class */ (function () {
  53151. /**
  53152. * Creates a new ActionEvent
  53153. * @param source The mesh or sprite that triggered the action
  53154. * @param pointerX The X mouse cursor position at the time of the event
  53155. * @param pointerY The Y mouse cursor position at the time of the event
  53156. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53157. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53158. * @param additionalData additional data for the event
  53159. */
  53160. function ActionEvent(
  53161. /** The mesh or sprite that triggered the action */
  53162. source,
  53163. /** The X mouse cursor position at the time of the event */
  53164. pointerX,
  53165. /** The Y mouse cursor position at the time of the event */
  53166. pointerY,
  53167. /** The mesh that is currently pointed at (can be null) */
  53168. meshUnderPointer,
  53169. /** the original (browser) event that triggered the ActionEvent */
  53170. sourceEvent,
  53171. /** additional data for the event */
  53172. additionalData) {
  53173. this.source = source;
  53174. this.pointerX = pointerX;
  53175. this.pointerY = pointerY;
  53176. this.meshUnderPointer = meshUnderPointer;
  53177. this.sourceEvent = sourceEvent;
  53178. this.additionalData = additionalData;
  53179. }
  53180. /**
  53181. * Helper function to auto-create an ActionEvent from a source mesh.
  53182. * @param source The source mesh that triggered the event
  53183. * @param evt The original (browser) event
  53184. * @param additionalData additional data for the event
  53185. * @returns the new ActionEvent
  53186. */
  53187. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53188. var scene = source.getScene();
  53189. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53190. };
  53191. /**
  53192. * Helper function to auto-create an ActionEvent from a source sprite
  53193. * @param source The source sprite that triggered the event
  53194. * @param scene Scene associated with the sprite
  53195. * @param evt The original (browser) event
  53196. * @param additionalData additional data for the event
  53197. * @returns the new ActionEvent
  53198. */
  53199. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53200. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53201. };
  53202. /**
  53203. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53204. * @param scene the scene where the event occurred
  53205. * @param evt The original (browser) event
  53206. * @returns the new ActionEvent
  53207. */
  53208. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53209. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53210. };
  53211. /**
  53212. * Helper function to auto-create an ActionEvent from a primitive
  53213. * @param prim defines the target primitive
  53214. * @param pointerPos defines the pointer position
  53215. * @param evt The original (browser) event
  53216. * @param additionalData additional data for the event
  53217. * @returns the new ActionEvent
  53218. */
  53219. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53220. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53221. };
  53222. return ActionEvent;
  53223. }());
  53224. BABYLON.ActionEvent = ActionEvent;
  53225. /**
  53226. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53227. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53228. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53229. */
  53230. var ActionManager = /** @class */ (function () {
  53231. /**
  53232. * Creates a new action manager
  53233. * @param scene defines the hosting scene
  53234. */
  53235. function ActionManager(scene) {
  53236. // Members
  53237. /** Gets the list of actions */
  53238. this.actions = new Array();
  53239. /** Gets the cursor to use when hovering items */
  53240. this.hoverCursor = '';
  53241. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53242. scene._actionManagers.push(this);
  53243. }
  53244. Object.defineProperty(ActionManager, "NothingTrigger", {
  53245. /**
  53246. * Nothing
  53247. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53248. */
  53249. get: function () {
  53250. return ActionManager._NothingTrigger;
  53251. },
  53252. enumerable: true,
  53253. configurable: true
  53254. });
  53255. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53256. /**
  53257. * On pick
  53258. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53259. */
  53260. get: function () {
  53261. return ActionManager._OnPickTrigger;
  53262. },
  53263. enumerable: true,
  53264. configurable: true
  53265. });
  53266. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53267. /**
  53268. * On left pick
  53269. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53270. */
  53271. get: function () {
  53272. return ActionManager._OnLeftPickTrigger;
  53273. },
  53274. enumerable: true,
  53275. configurable: true
  53276. });
  53277. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53278. /**
  53279. * On right pick
  53280. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53281. */
  53282. get: function () {
  53283. return ActionManager._OnRightPickTrigger;
  53284. },
  53285. enumerable: true,
  53286. configurable: true
  53287. });
  53288. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53289. /**
  53290. * On center pick
  53291. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53292. */
  53293. get: function () {
  53294. return ActionManager._OnCenterPickTrigger;
  53295. },
  53296. enumerable: true,
  53297. configurable: true
  53298. });
  53299. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53300. /**
  53301. * On pick down
  53302. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53303. */
  53304. get: function () {
  53305. return ActionManager._OnPickDownTrigger;
  53306. },
  53307. enumerable: true,
  53308. configurable: true
  53309. });
  53310. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53311. /**
  53312. * On double pick
  53313. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53314. */
  53315. get: function () {
  53316. return ActionManager._OnDoublePickTrigger;
  53317. },
  53318. enumerable: true,
  53319. configurable: true
  53320. });
  53321. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53322. /**
  53323. * On pick up
  53324. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53325. */
  53326. get: function () {
  53327. return ActionManager._OnPickUpTrigger;
  53328. },
  53329. enumerable: true,
  53330. configurable: true
  53331. });
  53332. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53333. /**
  53334. * On pick out.
  53335. * This trigger will only be raised if you also declared a OnPickDown
  53336. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53337. */
  53338. get: function () {
  53339. return ActionManager._OnPickOutTrigger;
  53340. },
  53341. enumerable: true,
  53342. configurable: true
  53343. });
  53344. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53345. /**
  53346. * On long press
  53347. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53348. */
  53349. get: function () {
  53350. return ActionManager._OnLongPressTrigger;
  53351. },
  53352. enumerable: true,
  53353. configurable: true
  53354. });
  53355. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53356. /**
  53357. * On pointer over
  53358. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53359. */
  53360. get: function () {
  53361. return ActionManager._OnPointerOverTrigger;
  53362. },
  53363. enumerable: true,
  53364. configurable: true
  53365. });
  53366. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53367. /**
  53368. * On pointer out
  53369. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53370. */
  53371. get: function () {
  53372. return ActionManager._OnPointerOutTrigger;
  53373. },
  53374. enumerable: true,
  53375. configurable: true
  53376. });
  53377. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53378. /**
  53379. * On every frame
  53380. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53381. */
  53382. get: function () {
  53383. return ActionManager._OnEveryFrameTrigger;
  53384. },
  53385. enumerable: true,
  53386. configurable: true
  53387. });
  53388. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53389. /**
  53390. * On intersection enter
  53391. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53392. */
  53393. get: function () {
  53394. return ActionManager._OnIntersectionEnterTrigger;
  53395. },
  53396. enumerable: true,
  53397. configurable: true
  53398. });
  53399. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53400. /**
  53401. * On intersection exit
  53402. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53403. */
  53404. get: function () {
  53405. return ActionManager._OnIntersectionExitTrigger;
  53406. },
  53407. enumerable: true,
  53408. configurable: true
  53409. });
  53410. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53411. /**
  53412. * On key down
  53413. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53414. */
  53415. get: function () {
  53416. return ActionManager._OnKeyDownTrigger;
  53417. },
  53418. enumerable: true,
  53419. configurable: true
  53420. });
  53421. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53422. /**
  53423. * On key up
  53424. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53425. */
  53426. get: function () {
  53427. return ActionManager._OnKeyUpTrigger;
  53428. },
  53429. enumerable: true,
  53430. configurable: true
  53431. });
  53432. // Methods
  53433. /**
  53434. * Releases all associated resources
  53435. */
  53436. ActionManager.prototype.dispose = function () {
  53437. var index = this._scene._actionManagers.indexOf(this);
  53438. for (var i = 0; i < this.actions.length; i++) {
  53439. var action = this.actions[i];
  53440. ActionManager.Triggers[action.trigger]--;
  53441. if (ActionManager.Triggers[action.trigger] === 0) {
  53442. delete ActionManager.Triggers[action.trigger];
  53443. }
  53444. }
  53445. if (index > -1) {
  53446. this._scene._actionManagers.splice(index, 1);
  53447. }
  53448. };
  53449. /**
  53450. * Gets hosting scene
  53451. * @returns the hosting scene
  53452. */
  53453. ActionManager.prototype.getScene = function () {
  53454. return this._scene;
  53455. };
  53456. /**
  53457. * Does this action manager handles actions of any of the given triggers
  53458. * @param triggers defines the triggers to be tested
  53459. * @return a boolean indicating whether one (or more) of the triggers is handled
  53460. */
  53461. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53462. for (var index = 0; index < this.actions.length; index++) {
  53463. var action = this.actions[index];
  53464. if (triggers.indexOf(action.trigger) > -1) {
  53465. return true;
  53466. }
  53467. }
  53468. return false;
  53469. };
  53470. /**
  53471. * Does this action manager handles actions of a given trigger
  53472. * @param trigger defines the trigger to be tested
  53473. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53474. * @return whether the trigger is handled
  53475. */
  53476. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53477. for (var index = 0; index < this.actions.length; index++) {
  53478. var action = this.actions[index];
  53479. if (action.trigger === trigger) {
  53480. if (parameterPredicate) {
  53481. if (parameterPredicate(action.getTriggerParameter())) {
  53482. return true;
  53483. }
  53484. }
  53485. else {
  53486. return true;
  53487. }
  53488. }
  53489. }
  53490. return false;
  53491. };
  53492. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53493. /**
  53494. * Does this action manager has pointer triggers
  53495. */
  53496. get: function () {
  53497. for (var index = 0; index < this.actions.length; index++) {
  53498. var action = this.actions[index];
  53499. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53500. return true;
  53501. }
  53502. }
  53503. return false;
  53504. },
  53505. enumerable: true,
  53506. configurable: true
  53507. });
  53508. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53509. /**
  53510. * Does this action manager has pick triggers
  53511. */
  53512. get: function () {
  53513. for (var index = 0; index < this.actions.length; index++) {
  53514. var action = this.actions[index];
  53515. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53516. return true;
  53517. }
  53518. }
  53519. return false;
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. Object.defineProperty(ActionManager, "HasTriggers", {
  53525. /**
  53526. * Does exist one action manager with at least one trigger
  53527. **/
  53528. get: function () {
  53529. for (var t in ActionManager.Triggers) {
  53530. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53531. return true;
  53532. }
  53533. }
  53534. return false;
  53535. },
  53536. enumerable: true,
  53537. configurable: true
  53538. });
  53539. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53540. /**
  53541. * Does exist one action manager with at least one pick trigger
  53542. **/
  53543. get: function () {
  53544. for (var t in ActionManager.Triggers) {
  53545. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53546. var t_int = parseInt(t);
  53547. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53548. return true;
  53549. }
  53550. }
  53551. }
  53552. return false;
  53553. },
  53554. enumerable: true,
  53555. configurable: true
  53556. });
  53557. /**
  53558. * Does exist one action manager that handles actions of a given trigger
  53559. * @param trigger defines the trigger to be tested
  53560. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53561. **/
  53562. ActionManager.HasSpecificTrigger = function (trigger) {
  53563. for (var t in ActionManager.Triggers) {
  53564. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53565. var t_int = parseInt(t);
  53566. if (t_int === trigger) {
  53567. return true;
  53568. }
  53569. }
  53570. }
  53571. return false;
  53572. };
  53573. /**
  53574. * Registers an action to this action manager
  53575. * @param action defines the action to be registered
  53576. * @return the action amended (prepared) after registration
  53577. */
  53578. ActionManager.prototype.registerAction = function (action) {
  53579. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53580. if (this.getScene().actionManager !== this) {
  53581. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53582. return null;
  53583. }
  53584. }
  53585. this.actions.push(action);
  53586. if (ActionManager.Triggers[action.trigger]) {
  53587. ActionManager.Triggers[action.trigger]++;
  53588. }
  53589. else {
  53590. ActionManager.Triggers[action.trigger] = 1;
  53591. }
  53592. action._actionManager = this;
  53593. action._prepare();
  53594. return action;
  53595. };
  53596. /**
  53597. * Unregisters an action to this action manager
  53598. * @param action defines the action to be unregistered
  53599. * @return a boolean indicating whether the action has been unregistered
  53600. */
  53601. ActionManager.prototype.unregisterAction = function (action) {
  53602. var index = this.actions.indexOf(action);
  53603. if (index !== -1) {
  53604. this.actions.splice(index, 1);
  53605. ActionManager.Triggers[action.trigger] -= 1;
  53606. if (ActionManager.Triggers[action.trigger] === 0) {
  53607. delete ActionManager.Triggers[action.trigger];
  53608. }
  53609. delete action._actionManager;
  53610. return true;
  53611. }
  53612. return false;
  53613. };
  53614. /**
  53615. * Process a specific trigger
  53616. * @param trigger defines the trigger to process
  53617. * @param evt defines the event details to be processed
  53618. */
  53619. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53620. for (var index = 0; index < this.actions.length; index++) {
  53621. var action = this.actions[index];
  53622. if (action.trigger === trigger) {
  53623. if (evt) {
  53624. if (trigger === ActionManager.OnKeyUpTrigger
  53625. || trigger === ActionManager.OnKeyDownTrigger) {
  53626. var parameter = action.getTriggerParameter();
  53627. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53628. if (!parameter.toLowerCase) {
  53629. continue;
  53630. }
  53631. var lowerCase = parameter.toLowerCase();
  53632. if (lowerCase !== evt.sourceEvent.key) {
  53633. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53634. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53635. if (actualkey !== lowerCase) {
  53636. continue;
  53637. }
  53638. }
  53639. }
  53640. }
  53641. }
  53642. action._executeCurrent(evt);
  53643. }
  53644. }
  53645. };
  53646. /** @hidden */
  53647. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53648. var properties = propertyPath.split(".");
  53649. for (var index = 0; index < properties.length - 1; index++) {
  53650. target = target[properties[index]];
  53651. }
  53652. return target;
  53653. };
  53654. /** @hidden */
  53655. ActionManager.prototype._getProperty = function (propertyPath) {
  53656. var properties = propertyPath.split(".");
  53657. return properties[properties.length - 1];
  53658. };
  53659. /**
  53660. * Serialize this manager to a JSON object
  53661. * @param name defines the property name to store this manager
  53662. * @returns a JSON representation of this manager
  53663. */
  53664. ActionManager.prototype.serialize = function (name) {
  53665. var root = {
  53666. children: new Array(),
  53667. name: name,
  53668. type: 3,
  53669. properties: new Array() // Empty for root but required
  53670. };
  53671. for (var i = 0; i < this.actions.length; i++) {
  53672. var triggerObject = {
  53673. type: 0,
  53674. children: new Array(),
  53675. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53676. properties: new Array()
  53677. };
  53678. var triggerOptions = this.actions[i].triggerOptions;
  53679. if (triggerOptions && typeof triggerOptions !== "number") {
  53680. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53681. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53682. }
  53683. else {
  53684. var parameter = {};
  53685. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53686. if (triggerOptions.parameter.mesh) {
  53687. parameter._meshId = triggerOptions.parameter.mesh.id;
  53688. }
  53689. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53690. }
  53691. }
  53692. // Serialize child action, recursively
  53693. this.actions[i].serialize(triggerObject);
  53694. // Add serialized trigger
  53695. root.children.push(triggerObject);
  53696. }
  53697. return root;
  53698. };
  53699. /**
  53700. * Creates a new ActionManager from a JSON data
  53701. * @param parsedActions defines the JSON data to read from
  53702. * @param object defines the hosting mesh
  53703. * @param scene defines the hosting scene
  53704. */
  53705. ActionManager.Parse = function (parsedActions, object, scene) {
  53706. var actionManager = new ActionManager(scene);
  53707. if (object === null)
  53708. scene.actionManager = actionManager;
  53709. else
  53710. object.actionManager = actionManager;
  53711. // instanciate a new object
  53712. var instanciate = function (name, params) {
  53713. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53714. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53715. newInstance.constructor.apply(newInstance, params);
  53716. return newInstance;
  53717. };
  53718. var parseParameter = function (name, value, target, propertyPath) {
  53719. if (propertyPath === null) {
  53720. // String, boolean or float
  53721. var floatValue = parseFloat(value);
  53722. if (value === "true" || value === "false")
  53723. return value === "true";
  53724. else
  53725. return isNaN(floatValue) ? value : floatValue;
  53726. }
  53727. var effectiveTarget = propertyPath.split(".");
  53728. var values = value.split(",");
  53729. // Get effective Target
  53730. for (var i = 0; i < effectiveTarget.length; i++) {
  53731. target = target[effectiveTarget[i]];
  53732. }
  53733. // Return appropriate value with its type
  53734. if (typeof (target) === "boolean")
  53735. return values[0] === "true";
  53736. if (typeof (target) === "string")
  53737. return values[0];
  53738. // Parameters with multiple values such as Vector3 etc.
  53739. var split = new Array();
  53740. for (var i = 0; i < values.length; i++)
  53741. split.push(parseFloat(values[i]));
  53742. if (target instanceof BABYLON.Vector3)
  53743. return BABYLON.Vector3.FromArray(split);
  53744. if (target instanceof BABYLON.Vector4)
  53745. return BABYLON.Vector4.FromArray(split);
  53746. if (target instanceof BABYLON.Color3)
  53747. return BABYLON.Color3.FromArray(split);
  53748. if (target instanceof BABYLON.Color4)
  53749. return BABYLON.Color4.FromArray(split);
  53750. return parseFloat(values[0]);
  53751. };
  53752. // traverse graph per trigger
  53753. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53754. if (combineArray === void 0) { combineArray = null; }
  53755. if (parsedAction.detached)
  53756. return;
  53757. var parameters = new Array();
  53758. var target = null;
  53759. var propertyPath = null;
  53760. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53761. // Parameters
  53762. if (parsedAction.type === 2)
  53763. parameters.push(actionManager);
  53764. else
  53765. parameters.push(trigger);
  53766. if (combine) {
  53767. var actions = new Array();
  53768. for (var j = 0; j < parsedAction.combine.length; j++) {
  53769. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53770. }
  53771. parameters.push(actions);
  53772. }
  53773. else {
  53774. for (var i = 0; i < parsedAction.properties.length; i++) {
  53775. var value = parsedAction.properties[i].value;
  53776. var name = parsedAction.properties[i].name;
  53777. var targetType = parsedAction.properties[i].targetType;
  53778. if (name === "target")
  53779. if (targetType !== null && targetType === "SceneProperties")
  53780. value = target = scene;
  53781. else
  53782. value = target = scene.getNodeByName(value);
  53783. else if (name === "parent")
  53784. value = scene.getNodeByName(value);
  53785. else if (name === "sound")
  53786. value = scene.getSoundByName(value);
  53787. else if (name !== "propertyPath") {
  53788. if (parsedAction.type === 2 && name === "operator")
  53789. value = BABYLON.ValueCondition[value];
  53790. else
  53791. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53792. }
  53793. else {
  53794. propertyPath = value;
  53795. }
  53796. parameters.push(value);
  53797. }
  53798. }
  53799. if (combineArray === null) {
  53800. parameters.push(condition);
  53801. }
  53802. else {
  53803. parameters.push(null);
  53804. }
  53805. // If interpolate value action
  53806. if (parsedAction.name === "InterpolateValueAction") {
  53807. var param = parameters[parameters.length - 2];
  53808. parameters[parameters.length - 1] = param;
  53809. parameters[parameters.length - 2] = condition;
  53810. }
  53811. // Action or condition(s) and not CombineAction
  53812. var newAction = instanciate(parsedAction.name, parameters);
  53813. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53814. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53815. if (action)
  53816. action.then(nothing);
  53817. else
  53818. actionManager.registerAction(nothing);
  53819. action = nothing;
  53820. }
  53821. if (combineArray === null) {
  53822. if (newAction instanceof BABYLON.Condition) {
  53823. condition = newAction;
  53824. newAction = action;
  53825. }
  53826. else {
  53827. condition = null;
  53828. if (action)
  53829. action.then(newAction);
  53830. else
  53831. actionManager.registerAction(newAction);
  53832. }
  53833. }
  53834. else {
  53835. combineArray.push(newAction);
  53836. }
  53837. for (var i = 0; i < parsedAction.children.length; i++)
  53838. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53839. };
  53840. // triggers
  53841. for (var i = 0; i < parsedActions.children.length; i++) {
  53842. var triggerParams;
  53843. var trigger = parsedActions.children[i];
  53844. if (trigger.properties.length > 0) {
  53845. var param = trigger.properties[0].value;
  53846. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53847. if (value._meshId) {
  53848. value.mesh = scene.getMeshByID(value._meshId);
  53849. }
  53850. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53851. }
  53852. else
  53853. triggerParams = ActionManager[trigger.name];
  53854. for (var j = 0; j < trigger.children.length; j++) {
  53855. if (!trigger.detached)
  53856. traverse(trigger.children[j], triggerParams, null, null);
  53857. }
  53858. }
  53859. };
  53860. /**
  53861. * Get a trigger name by index
  53862. * @param trigger defines the trigger index
  53863. * @returns a trigger name
  53864. */
  53865. ActionManager.GetTriggerName = function (trigger) {
  53866. switch (trigger) {
  53867. case 0: return "NothingTrigger";
  53868. case 1: return "OnPickTrigger";
  53869. case 2: return "OnLeftPickTrigger";
  53870. case 3: return "OnRightPickTrigger";
  53871. case 4: return "OnCenterPickTrigger";
  53872. case 5: return "OnPickDownTrigger";
  53873. case 6: return "OnPickUpTrigger";
  53874. case 7: return "OnLongPressTrigger";
  53875. case 8: return "OnPointerOverTrigger";
  53876. case 9: return "OnPointerOutTrigger";
  53877. case 10: return "OnEveryFrameTrigger";
  53878. case 11: return "OnIntersectionEnterTrigger";
  53879. case 12: return "OnIntersectionExitTrigger";
  53880. case 13: return "OnKeyDownTrigger";
  53881. case 14: return "OnKeyUpTrigger";
  53882. case 15: return "OnPickOutTrigger";
  53883. default: return "";
  53884. }
  53885. };
  53886. // Statics
  53887. ActionManager._NothingTrigger = 0;
  53888. ActionManager._OnPickTrigger = 1;
  53889. ActionManager._OnLeftPickTrigger = 2;
  53890. ActionManager._OnRightPickTrigger = 3;
  53891. ActionManager._OnCenterPickTrigger = 4;
  53892. ActionManager._OnPickDownTrigger = 5;
  53893. ActionManager._OnDoublePickTrigger = 6;
  53894. ActionManager._OnPickUpTrigger = 7;
  53895. ActionManager._OnLongPressTrigger = 8;
  53896. ActionManager._OnPointerOverTrigger = 9;
  53897. ActionManager._OnPointerOutTrigger = 10;
  53898. ActionManager._OnEveryFrameTrigger = 11;
  53899. ActionManager._OnIntersectionEnterTrigger = 12;
  53900. ActionManager._OnIntersectionExitTrigger = 13;
  53901. ActionManager._OnKeyDownTrigger = 14;
  53902. ActionManager._OnKeyUpTrigger = 15;
  53903. ActionManager._OnPickOutTrigger = 16;
  53904. /** Gets the list of active triggers */
  53905. ActionManager.Triggers = {};
  53906. return ActionManager;
  53907. }());
  53908. BABYLON.ActionManager = ActionManager;
  53909. })(BABYLON || (BABYLON = {}));
  53910. //# sourceMappingURL=babylon.actionManager.js.map
  53911. var BABYLON;
  53912. (function (BABYLON) {
  53913. var InterpolateValueAction = /** @class */ (function (_super) {
  53914. __extends(InterpolateValueAction, _super);
  53915. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53916. if (duration === void 0) { duration = 1000; }
  53917. var _this = _super.call(this, triggerOptions, condition) || this;
  53918. _this.propertyPath = propertyPath;
  53919. _this.value = value;
  53920. _this.duration = duration;
  53921. _this.stopOtherAnimations = stopOtherAnimations;
  53922. _this.onInterpolationDone = onInterpolationDone;
  53923. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53924. _this._target = _this._effectiveTarget = target;
  53925. return _this;
  53926. }
  53927. InterpolateValueAction.prototype._prepare = function () {
  53928. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53929. this._property = this._getProperty(this.propertyPath);
  53930. };
  53931. InterpolateValueAction.prototype.execute = function () {
  53932. var _this = this;
  53933. var scene = this._actionManager.getScene();
  53934. var keys = [
  53935. {
  53936. frame: 0,
  53937. value: this._effectiveTarget[this._property]
  53938. }, {
  53939. frame: 100,
  53940. value: this.value
  53941. }
  53942. ];
  53943. var dataType;
  53944. if (typeof this.value === "number") {
  53945. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53946. }
  53947. else if (this.value instanceof BABYLON.Color3) {
  53948. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53949. }
  53950. else if (this.value instanceof BABYLON.Vector3) {
  53951. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53952. }
  53953. else if (this.value instanceof BABYLON.Matrix) {
  53954. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53955. }
  53956. else if (this.value instanceof BABYLON.Quaternion) {
  53957. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53958. }
  53959. else {
  53960. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53961. return;
  53962. }
  53963. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53964. animation.setKeys(keys);
  53965. if (this.stopOtherAnimations) {
  53966. scene.stopAnimation(this._effectiveTarget);
  53967. }
  53968. var wrapper = function () {
  53969. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53970. if (_this.onInterpolationDone) {
  53971. _this.onInterpolationDone();
  53972. }
  53973. };
  53974. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53975. };
  53976. InterpolateValueAction.prototype.serialize = function (parent) {
  53977. return _super.prototype._serialize.call(this, {
  53978. name: "InterpolateValueAction",
  53979. properties: [
  53980. BABYLON.Action._GetTargetProperty(this._target),
  53981. { name: "propertyPath", value: this.propertyPath },
  53982. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53983. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53984. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53985. ]
  53986. }, parent);
  53987. };
  53988. return InterpolateValueAction;
  53989. }(BABYLON.Action));
  53990. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53991. })(BABYLON || (BABYLON = {}));
  53992. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53993. var BABYLON;
  53994. (function (BABYLON) {
  53995. var SwitchBooleanAction = /** @class */ (function (_super) {
  53996. __extends(SwitchBooleanAction, _super);
  53997. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53998. var _this = _super.call(this, triggerOptions, condition) || this;
  53999. _this.propertyPath = propertyPath;
  54000. _this._target = _this._effectiveTarget = target;
  54001. return _this;
  54002. }
  54003. SwitchBooleanAction.prototype._prepare = function () {
  54004. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54005. this._property = this._getProperty(this.propertyPath);
  54006. };
  54007. SwitchBooleanAction.prototype.execute = function () {
  54008. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54009. };
  54010. SwitchBooleanAction.prototype.serialize = function (parent) {
  54011. return _super.prototype._serialize.call(this, {
  54012. name: "SwitchBooleanAction",
  54013. properties: [
  54014. BABYLON.Action._GetTargetProperty(this._target),
  54015. { name: "propertyPath", value: this.propertyPath }
  54016. ]
  54017. }, parent);
  54018. };
  54019. return SwitchBooleanAction;
  54020. }(BABYLON.Action));
  54021. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54022. var SetStateAction = /** @class */ (function (_super) {
  54023. __extends(SetStateAction, _super);
  54024. function SetStateAction(triggerOptions, target, value, condition) {
  54025. var _this = _super.call(this, triggerOptions, condition) || this;
  54026. _this.value = value;
  54027. _this._target = target;
  54028. return _this;
  54029. }
  54030. SetStateAction.prototype.execute = function () {
  54031. this._target.state = this.value;
  54032. };
  54033. SetStateAction.prototype.serialize = function (parent) {
  54034. return _super.prototype._serialize.call(this, {
  54035. name: "SetStateAction",
  54036. properties: [
  54037. BABYLON.Action._GetTargetProperty(this._target),
  54038. { name: "value", value: this.value }
  54039. ]
  54040. }, parent);
  54041. };
  54042. return SetStateAction;
  54043. }(BABYLON.Action));
  54044. BABYLON.SetStateAction = SetStateAction;
  54045. var SetValueAction = /** @class */ (function (_super) {
  54046. __extends(SetValueAction, _super);
  54047. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54048. var _this = _super.call(this, triggerOptions, condition) || this;
  54049. _this.propertyPath = propertyPath;
  54050. _this.value = value;
  54051. _this._target = _this._effectiveTarget = target;
  54052. return _this;
  54053. }
  54054. SetValueAction.prototype._prepare = function () {
  54055. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54056. this._property = this._getProperty(this.propertyPath);
  54057. };
  54058. SetValueAction.prototype.execute = function () {
  54059. this._effectiveTarget[this._property] = this.value;
  54060. if (this._target.markAsDirty) {
  54061. this._target.markAsDirty(this._property);
  54062. }
  54063. };
  54064. SetValueAction.prototype.serialize = function (parent) {
  54065. return _super.prototype._serialize.call(this, {
  54066. name: "SetValueAction",
  54067. properties: [
  54068. BABYLON.Action._GetTargetProperty(this._target),
  54069. { name: "propertyPath", value: this.propertyPath },
  54070. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54071. ]
  54072. }, parent);
  54073. };
  54074. return SetValueAction;
  54075. }(BABYLON.Action));
  54076. BABYLON.SetValueAction = SetValueAction;
  54077. var IncrementValueAction = /** @class */ (function (_super) {
  54078. __extends(IncrementValueAction, _super);
  54079. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54080. var _this = _super.call(this, triggerOptions, condition) || this;
  54081. _this.propertyPath = propertyPath;
  54082. _this.value = value;
  54083. _this._target = _this._effectiveTarget = target;
  54084. return _this;
  54085. }
  54086. IncrementValueAction.prototype._prepare = function () {
  54087. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54088. this._property = this._getProperty(this.propertyPath);
  54089. if (typeof this._effectiveTarget[this._property] !== "number") {
  54090. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54091. }
  54092. };
  54093. IncrementValueAction.prototype.execute = function () {
  54094. this._effectiveTarget[this._property] += this.value;
  54095. if (this._target.markAsDirty) {
  54096. this._target.markAsDirty(this._property);
  54097. }
  54098. };
  54099. IncrementValueAction.prototype.serialize = function (parent) {
  54100. return _super.prototype._serialize.call(this, {
  54101. name: "IncrementValueAction",
  54102. properties: [
  54103. BABYLON.Action._GetTargetProperty(this._target),
  54104. { name: "propertyPath", value: this.propertyPath },
  54105. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54106. ]
  54107. }, parent);
  54108. };
  54109. return IncrementValueAction;
  54110. }(BABYLON.Action));
  54111. BABYLON.IncrementValueAction = IncrementValueAction;
  54112. var PlayAnimationAction = /** @class */ (function (_super) {
  54113. __extends(PlayAnimationAction, _super);
  54114. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54115. var _this = _super.call(this, triggerOptions, condition) || this;
  54116. _this.from = from;
  54117. _this.to = to;
  54118. _this.loop = loop;
  54119. _this._target = target;
  54120. return _this;
  54121. }
  54122. PlayAnimationAction.prototype._prepare = function () {
  54123. };
  54124. PlayAnimationAction.prototype.execute = function () {
  54125. var scene = this._actionManager.getScene();
  54126. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54127. };
  54128. PlayAnimationAction.prototype.serialize = function (parent) {
  54129. return _super.prototype._serialize.call(this, {
  54130. name: "PlayAnimationAction",
  54131. properties: [
  54132. BABYLON.Action._GetTargetProperty(this._target),
  54133. { name: "from", value: String(this.from) },
  54134. { name: "to", value: String(this.to) },
  54135. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54136. ]
  54137. }, parent);
  54138. };
  54139. return PlayAnimationAction;
  54140. }(BABYLON.Action));
  54141. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54142. var StopAnimationAction = /** @class */ (function (_super) {
  54143. __extends(StopAnimationAction, _super);
  54144. function StopAnimationAction(triggerOptions, target, condition) {
  54145. var _this = _super.call(this, triggerOptions, condition) || this;
  54146. _this._target = target;
  54147. return _this;
  54148. }
  54149. StopAnimationAction.prototype._prepare = function () {
  54150. };
  54151. StopAnimationAction.prototype.execute = function () {
  54152. var scene = this._actionManager.getScene();
  54153. scene.stopAnimation(this._target);
  54154. };
  54155. StopAnimationAction.prototype.serialize = function (parent) {
  54156. return _super.prototype._serialize.call(this, {
  54157. name: "StopAnimationAction",
  54158. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54159. }, parent);
  54160. };
  54161. return StopAnimationAction;
  54162. }(BABYLON.Action));
  54163. BABYLON.StopAnimationAction = StopAnimationAction;
  54164. var DoNothingAction = /** @class */ (function (_super) {
  54165. __extends(DoNothingAction, _super);
  54166. function DoNothingAction(triggerOptions, condition) {
  54167. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54168. return _super.call(this, triggerOptions, condition) || this;
  54169. }
  54170. DoNothingAction.prototype.execute = function () {
  54171. };
  54172. DoNothingAction.prototype.serialize = function (parent) {
  54173. return _super.prototype._serialize.call(this, {
  54174. name: "DoNothingAction",
  54175. properties: []
  54176. }, parent);
  54177. };
  54178. return DoNothingAction;
  54179. }(BABYLON.Action));
  54180. BABYLON.DoNothingAction = DoNothingAction;
  54181. var CombineAction = /** @class */ (function (_super) {
  54182. __extends(CombineAction, _super);
  54183. function CombineAction(triggerOptions, children, condition) {
  54184. var _this = _super.call(this, triggerOptions, condition) || this;
  54185. _this.children = children;
  54186. return _this;
  54187. }
  54188. CombineAction.prototype._prepare = function () {
  54189. for (var index = 0; index < this.children.length; index++) {
  54190. this.children[index]._actionManager = this._actionManager;
  54191. this.children[index]._prepare();
  54192. }
  54193. };
  54194. CombineAction.prototype.execute = function (evt) {
  54195. for (var index = 0; index < this.children.length; index++) {
  54196. this.children[index].execute(evt);
  54197. }
  54198. };
  54199. CombineAction.prototype.serialize = function (parent) {
  54200. var serializationObject = _super.prototype._serialize.call(this, {
  54201. name: "CombineAction",
  54202. properties: [],
  54203. combine: []
  54204. }, parent);
  54205. for (var i = 0; i < this.children.length; i++) {
  54206. serializationObject.combine.push(this.children[i].serialize(null));
  54207. }
  54208. return serializationObject;
  54209. };
  54210. return CombineAction;
  54211. }(BABYLON.Action));
  54212. BABYLON.CombineAction = CombineAction;
  54213. var ExecuteCodeAction = /** @class */ (function (_super) {
  54214. __extends(ExecuteCodeAction, _super);
  54215. function ExecuteCodeAction(triggerOptions, func, condition) {
  54216. var _this = _super.call(this, triggerOptions, condition) || this;
  54217. _this.func = func;
  54218. return _this;
  54219. }
  54220. ExecuteCodeAction.prototype.execute = function (evt) {
  54221. this.func(evt);
  54222. };
  54223. return ExecuteCodeAction;
  54224. }(BABYLON.Action));
  54225. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54226. var SetParentAction = /** @class */ (function (_super) {
  54227. __extends(SetParentAction, _super);
  54228. function SetParentAction(triggerOptions, target, parent, condition) {
  54229. var _this = _super.call(this, triggerOptions, condition) || this;
  54230. _this._target = target;
  54231. _this._parent = parent;
  54232. return _this;
  54233. }
  54234. SetParentAction.prototype._prepare = function () {
  54235. };
  54236. SetParentAction.prototype.execute = function () {
  54237. if (this._target.parent === this._parent) {
  54238. return;
  54239. }
  54240. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54241. invertParentWorldMatrix.invert();
  54242. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54243. this._target.parent = this._parent;
  54244. };
  54245. SetParentAction.prototype.serialize = function (parent) {
  54246. return _super.prototype._serialize.call(this, {
  54247. name: "SetParentAction",
  54248. properties: [
  54249. BABYLON.Action._GetTargetProperty(this._target),
  54250. BABYLON.Action._GetTargetProperty(this._parent),
  54251. ]
  54252. }, parent);
  54253. };
  54254. return SetParentAction;
  54255. }(BABYLON.Action));
  54256. BABYLON.SetParentAction = SetParentAction;
  54257. var PlaySoundAction = /** @class */ (function (_super) {
  54258. __extends(PlaySoundAction, _super);
  54259. function PlaySoundAction(triggerOptions, sound, condition) {
  54260. var _this = _super.call(this, triggerOptions, condition) || this;
  54261. _this._sound = sound;
  54262. return _this;
  54263. }
  54264. PlaySoundAction.prototype._prepare = function () {
  54265. };
  54266. PlaySoundAction.prototype.execute = function () {
  54267. if (this._sound !== undefined)
  54268. this._sound.play();
  54269. };
  54270. PlaySoundAction.prototype.serialize = function (parent) {
  54271. return _super.prototype._serialize.call(this, {
  54272. name: "PlaySoundAction",
  54273. properties: [{ name: "sound", value: this._sound.name }]
  54274. }, parent);
  54275. };
  54276. return PlaySoundAction;
  54277. }(BABYLON.Action));
  54278. BABYLON.PlaySoundAction = PlaySoundAction;
  54279. var StopSoundAction = /** @class */ (function (_super) {
  54280. __extends(StopSoundAction, _super);
  54281. function StopSoundAction(triggerOptions, sound, condition) {
  54282. var _this = _super.call(this, triggerOptions, condition) || this;
  54283. _this._sound = sound;
  54284. return _this;
  54285. }
  54286. StopSoundAction.prototype._prepare = function () {
  54287. };
  54288. StopSoundAction.prototype.execute = function () {
  54289. if (this._sound !== undefined)
  54290. this._sound.stop();
  54291. };
  54292. StopSoundAction.prototype.serialize = function (parent) {
  54293. return _super.prototype._serialize.call(this, {
  54294. name: "StopSoundAction",
  54295. properties: [{ name: "sound", value: this._sound.name }]
  54296. }, parent);
  54297. };
  54298. return StopSoundAction;
  54299. }(BABYLON.Action));
  54300. BABYLON.StopSoundAction = StopSoundAction;
  54301. })(BABYLON || (BABYLON = {}));
  54302. //# sourceMappingURL=babylon.directActions.js.map
  54303. var BABYLON;
  54304. (function (BABYLON) {
  54305. var SpriteManager = /** @class */ (function () {
  54306. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54307. if (epsilon === void 0) { epsilon = 0.01; }
  54308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54309. this.name = name;
  54310. this.sprites = new Array();
  54311. this.renderingGroupId = 0;
  54312. this.layerMask = 0x0FFFFFFF;
  54313. this.fogEnabled = true;
  54314. this.isPickable = false;
  54315. /**
  54316. * An event triggered when the manager is disposed.
  54317. */
  54318. this.onDisposeObservable = new BABYLON.Observable();
  54319. this._vertexBuffers = {};
  54320. this._capacity = capacity;
  54321. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54322. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54323. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54324. if (cellSize.width && cellSize.height) {
  54325. this.cellWidth = cellSize.width;
  54326. this.cellHeight = cellSize.height;
  54327. }
  54328. else if (cellSize !== undefined) {
  54329. this.cellWidth = cellSize;
  54330. this.cellHeight = cellSize;
  54331. }
  54332. else {
  54333. return;
  54334. }
  54335. this._epsilon = epsilon;
  54336. this._scene = scene;
  54337. this._scene.spriteManagers.push(this);
  54338. var indices = [];
  54339. var index = 0;
  54340. for (var count = 0; count < capacity; count++) {
  54341. indices.push(index);
  54342. indices.push(index + 1);
  54343. indices.push(index + 2);
  54344. indices.push(index);
  54345. indices.push(index + 2);
  54346. indices.push(index + 3);
  54347. index += 4;
  54348. }
  54349. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54350. // VBO
  54351. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54352. this._vertexData = new Float32Array(capacity * 16 * 4);
  54353. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54354. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54355. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54356. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54357. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54358. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54359. this._vertexBuffers["options"] = options;
  54360. this._vertexBuffers["cellInfo"] = cellInfo;
  54361. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54362. // Effects
  54363. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54364. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54365. }
  54366. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54367. set: function (callback) {
  54368. if (this._onDisposeObserver) {
  54369. this.onDisposeObservable.remove(this._onDisposeObserver);
  54370. }
  54371. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54372. },
  54373. enumerable: true,
  54374. configurable: true
  54375. });
  54376. Object.defineProperty(SpriteManager.prototype, "texture", {
  54377. get: function () {
  54378. return this._spriteTexture;
  54379. },
  54380. set: function (value) {
  54381. this._spriteTexture = value;
  54382. },
  54383. enumerable: true,
  54384. configurable: true
  54385. });
  54386. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54387. var arrayOffset = index * 16;
  54388. if (offsetX === 0)
  54389. offsetX = this._epsilon;
  54390. else if (offsetX === 1)
  54391. offsetX = 1 - this._epsilon;
  54392. if (offsetY === 0)
  54393. offsetY = this._epsilon;
  54394. else if (offsetY === 1)
  54395. offsetY = 1 - this._epsilon;
  54396. this._vertexData[arrayOffset] = sprite.position.x;
  54397. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54398. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54399. this._vertexData[arrayOffset + 3] = sprite.angle;
  54400. this._vertexData[arrayOffset + 4] = sprite.width;
  54401. this._vertexData[arrayOffset + 5] = sprite.height;
  54402. this._vertexData[arrayOffset + 6] = offsetX;
  54403. this._vertexData[arrayOffset + 7] = offsetY;
  54404. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54405. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54406. var offset = (sprite.cellIndex / rowSize) >> 0;
  54407. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54408. this._vertexData[arrayOffset + 11] = offset;
  54409. // Color
  54410. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54411. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54412. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54413. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54414. };
  54415. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54416. var count = Math.min(this._capacity, this.sprites.length);
  54417. var min = BABYLON.Vector3.Zero();
  54418. var max = BABYLON.Vector3.Zero();
  54419. var distance = Number.MAX_VALUE;
  54420. var currentSprite = null;
  54421. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54422. var cameraView = camera.getViewMatrix();
  54423. for (var index = 0; index < count; index++) {
  54424. var sprite = this.sprites[index];
  54425. if (!sprite) {
  54426. continue;
  54427. }
  54428. if (predicate) {
  54429. if (!predicate(sprite)) {
  54430. continue;
  54431. }
  54432. }
  54433. else if (!sprite.isPickable) {
  54434. continue;
  54435. }
  54436. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54437. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54438. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54439. if (ray.intersectsBoxMinMax(min, max)) {
  54440. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54441. if (distance > currentDistance) {
  54442. distance = currentDistance;
  54443. currentSprite = sprite;
  54444. if (fastCheck) {
  54445. break;
  54446. }
  54447. }
  54448. }
  54449. }
  54450. if (currentSprite) {
  54451. var result = new BABYLON.PickingInfo();
  54452. result.hit = true;
  54453. result.pickedSprite = currentSprite;
  54454. result.distance = distance;
  54455. return result;
  54456. }
  54457. return null;
  54458. };
  54459. SpriteManager.prototype.render = function () {
  54460. // Check
  54461. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54462. return;
  54463. var engine = this._scene.getEngine();
  54464. var baseSize = this._spriteTexture.getBaseSize();
  54465. // Sprites
  54466. var deltaTime = engine.getDeltaTime();
  54467. var max = Math.min(this._capacity, this.sprites.length);
  54468. var rowSize = baseSize.width / this.cellWidth;
  54469. var offset = 0;
  54470. for (var index = 0; index < max; index++) {
  54471. var sprite = this.sprites[index];
  54472. if (!sprite) {
  54473. continue;
  54474. }
  54475. sprite._animate(deltaTime);
  54476. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54477. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54478. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54479. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54480. }
  54481. this._buffer.update(this._vertexData);
  54482. // Render
  54483. var effect = this._effectBase;
  54484. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54485. effect = this._effectFog;
  54486. }
  54487. engine.enableEffect(effect);
  54488. var viewMatrix = this._scene.getViewMatrix();
  54489. effect.setTexture("diffuseSampler", this._spriteTexture);
  54490. effect.setMatrix("view", viewMatrix);
  54491. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54492. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54493. // Fog
  54494. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54495. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54496. effect.setColor3("vFogColor", this._scene.fogColor);
  54497. }
  54498. // VBOs
  54499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54500. // Draw order
  54501. engine.setDepthFunctionToLessOrEqual();
  54502. effect.setBool("alphaTest", true);
  54503. engine.setColorWrite(false);
  54504. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54505. engine.setColorWrite(true);
  54506. effect.setBool("alphaTest", false);
  54507. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54508. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54509. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54510. };
  54511. SpriteManager.prototype.dispose = function () {
  54512. if (this._buffer) {
  54513. this._buffer.dispose();
  54514. this._buffer = null;
  54515. }
  54516. if (this._indexBuffer) {
  54517. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54518. this._indexBuffer = null;
  54519. }
  54520. if (this._spriteTexture) {
  54521. this._spriteTexture.dispose();
  54522. this._spriteTexture = null;
  54523. }
  54524. // Remove from scene
  54525. var index = this._scene.spriteManagers.indexOf(this);
  54526. this._scene.spriteManagers.splice(index, 1);
  54527. // Callback
  54528. this.onDisposeObservable.notifyObservers(this);
  54529. this.onDisposeObservable.clear();
  54530. };
  54531. return SpriteManager;
  54532. }());
  54533. BABYLON.SpriteManager = SpriteManager;
  54534. })(BABYLON || (BABYLON = {}));
  54535. //# sourceMappingURL=babylon.spriteManager.js.map
  54536. var BABYLON;
  54537. (function (BABYLON) {
  54538. var Sprite = /** @class */ (function () {
  54539. function Sprite(name, manager) {
  54540. this.name = name;
  54541. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54542. this.width = 1.0;
  54543. this.height = 1.0;
  54544. this.angle = 0;
  54545. this.cellIndex = 0;
  54546. this.invertU = 0;
  54547. this.invertV = 0;
  54548. this.animations = new Array();
  54549. this.isPickable = false;
  54550. this._animationStarted = false;
  54551. this._loopAnimation = false;
  54552. this._fromIndex = 0;
  54553. this._toIndex = 0;
  54554. this._delay = 0;
  54555. this._direction = 1;
  54556. this._time = 0;
  54557. this._manager = manager;
  54558. this._manager.sprites.push(this);
  54559. this.position = BABYLON.Vector3.Zero();
  54560. }
  54561. Object.defineProperty(Sprite.prototype, "size", {
  54562. get: function () {
  54563. return this.width;
  54564. },
  54565. set: function (value) {
  54566. this.width = value;
  54567. this.height = value;
  54568. },
  54569. enumerable: true,
  54570. configurable: true
  54571. });
  54572. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54573. this._fromIndex = from;
  54574. this._toIndex = to;
  54575. this._loopAnimation = loop;
  54576. this._delay = delay;
  54577. this._animationStarted = true;
  54578. this._direction = from < to ? 1 : -1;
  54579. this.cellIndex = from;
  54580. this._time = 0;
  54581. this._onAnimationEnd = onAnimationEnd;
  54582. };
  54583. Sprite.prototype.stopAnimation = function () {
  54584. this._animationStarted = false;
  54585. };
  54586. Sprite.prototype._animate = function (deltaTime) {
  54587. if (!this._animationStarted)
  54588. return;
  54589. this._time += deltaTime;
  54590. if (this._time > this._delay) {
  54591. this._time = this._time % this._delay;
  54592. this.cellIndex += this._direction;
  54593. if (this.cellIndex > this._toIndex) {
  54594. if (this._loopAnimation) {
  54595. this.cellIndex = this._fromIndex;
  54596. }
  54597. else {
  54598. this.cellIndex = this._toIndex;
  54599. this._animationStarted = false;
  54600. if (this._onAnimationEnd) {
  54601. this._onAnimationEnd();
  54602. }
  54603. if (this.disposeWhenFinishedAnimating) {
  54604. this.dispose();
  54605. }
  54606. }
  54607. }
  54608. }
  54609. };
  54610. Sprite.prototype.dispose = function () {
  54611. for (var i = 0; i < this._manager.sprites.length; i++) {
  54612. if (this._manager.sprites[i] == this) {
  54613. this._manager.sprites.splice(i, 1);
  54614. }
  54615. }
  54616. };
  54617. return Sprite;
  54618. }());
  54619. BABYLON.Sprite = Sprite;
  54620. })(BABYLON || (BABYLON = {}));
  54621. //# sourceMappingURL=babylon.sprite.js.map
  54622. var BABYLON;
  54623. (function (BABYLON) {
  54624. var IntersectionInfo = /** @class */ (function () {
  54625. function IntersectionInfo(bu, bv, distance) {
  54626. this.bu = bu;
  54627. this.bv = bv;
  54628. this.distance = distance;
  54629. this.faceId = 0;
  54630. this.subMeshId = 0;
  54631. }
  54632. return IntersectionInfo;
  54633. }());
  54634. BABYLON.IntersectionInfo = IntersectionInfo;
  54635. var PickingInfo = /** @class */ (function () {
  54636. function PickingInfo() {
  54637. this.hit = false;
  54638. this.distance = 0;
  54639. this.pickedPoint = null;
  54640. this.pickedMesh = null;
  54641. this.bu = 0;
  54642. this.bv = 0;
  54643. this.faceId = -1;
  54644. this.subMeshId = 0;
  54645. this.pickedSprite = null;
  54646. }
  54647. // Methods
  54648. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54649. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54650. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54651. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54652. return null;
  54653. }
  54654. var indices = this.pickedMesh.getIndices();
  54655. if (!indices) {
  54656. return null;
  54657. }
  54658. var result;
  54659. if (useVerticesNormals) {
  54660. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54661. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54662. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54663. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54664. normal0 = normal0.scale(this.bu);
  54665. normal1 = normal1.scale(this.bv);
  54666. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54667. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54668. }
  54669. else {
  54670. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54671. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54672. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54673. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54674. var p1p2 = vertex1.subtract(vertex2);
  54675. var p3p2 = vertex3.subtract(vertex2);
  54676. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54677. }
  54678. if (useWorldCoordinates) {
  54679. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54680. }
  54681. return BABYLON.Vector3.Normalize(result);
  54682. };
  54683. PickingInfo.prototype.getTextureCoordinates = function () {
  54684. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54685. return null;
  54686. }
  54687. var indices = this.pickedMesh.getIndices();
  54688. if (!indices) {
  54689. return null;
  54690. }
  54691. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54692. if (!uvs) {
  54693. return null;
  54694. }
  54695. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54696. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54697. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54698. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54699. uv1 = uv1.scale(this.bu);
  54700. uv2 = uv2.scale(this.bv);
  54701. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54702. };
  54703. return PickingInfo;
  54704. }());
  54705. BABYLON.PickingInfo = PickingInfo;
  54706. })(BABYLON || (BABYLON = {}));
  54707. //# sourceMappingURL=babylon.pickingInfo.js.map
  54708. var BABYLON;
  54709. (function (BABYLON) {
  54710. var Ray = /** @class */ (function () {
  54711. function Ray(origin, direction, length) {
  54712. if (length === void 0) { length = Number.MAX_VALUE; }
  54713. this.origin = origin;
  54714. this.direction = direction;
  54715. this.length = length;
  54716. }
  54717. // Methods
  54718. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54719. var d = 0.0;
  54720. var maxValue = Number.MAX_VALUE;
  54721. var inv;
  54722. var min;
  54723. var max;
  54724. var temp;
  54725. if (Math.abs(this.direction.x) < 0.0000001) {
  54726. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54727. return false;
  54728. }
  54729. }
  54730. else {
  54731. inv = 1.0 / this.direction.x;
  54732. min = (minimum.x - this.origin.x) * inv;
  54733. max = (maximum.x - this.origin.x) * inv;
  54734. if (max === -Infinity) {
  54735. max = Infinity;
  54736. }
  54737. if (min > max) {
  54738. temp = min;
  54739. min = max;
  54740. max = temp;
  54741. }
  54742. d = Math.max(min, d);
  54743. maxValue = Math.min(max, maxValue);
  54744. if (d > maxValue) {
  54745. return false;
  54746. }
  54747. }
  54748. if (Math.abs(this.direction.y) < 0.0000001) {
  54749. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54750. return false;
  54751. }
  54752. }
  54753. else {
  54754. inv = 1.0 / this.direction.y;
  54755. min = (minimum.y - this.origin.y) * inv;
  54756. max = (maximum.y - this.origin.y) * inv;
  54757. if (max === -Infinity) {
  54758. max = Infinity;
  54759. }
  54760. if (min > max) {
  54761. temp = min;
  54762. min = max;
  54763. max = temp;
  54764. }
  54765. d = Math.max(min, d);
  54766. maxValue = Math.min(max, maxValue);
  54767. if (d > maxValue) {
  54768. return false;
  54769. }
  54770. }
  54771. if (Math.abs(this.direction.z) < 0.0000001) {
  54772. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54773. return false;
  54774. }
  54775. }
  54776. else {
  54777. inv = 1.0 / this.direction.z;
  54778. min = (minimum.z - this.origin.z) * inv;
  54779. max = (maximum.z - this.origin.z) * inv;
  54780. if (max === -Infinity) {
  54781. max = Infinity;
  54782. }
  54783. if (min > max) {
  54784. temp = min;
  54785. min = max;
  54786. max = temp;
  54787. }
  54788. d = Math.max(min, d);
  54789. maxValue = Math.min(max, maxValue);
  54790. if (d > maxValue) {
  54791. return false;
  54792. }
  54793. }
  54794. return true;
  54795. };
  54796. Ray.prototype.intersectsBox = function (box) {
  54797. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54798. };
  54799. Ray.prototype.intersectsSphere = function (sphere) {
  54800. var x = sphere.center.x - this.origin.x;
  54801. var y = sphere.center.y - this.origin.y;
  54802. var z = sphere.center.z - this.origin.z;
  54803. var pyth = (x * x) + (y * y) + (z * z);
  54804. var rr = sphere.radius * sphere.radius;
  54805. if (pyth <= rr) {
  54806. return true;
  54807. }
  54808. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54809. if (dot < 0.0) {
  54810. return false;
  54811. }
  54812. var temp = pyth - (dot * dot);
  54813. return temp <= rr;
  54814. };
  54815. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54816. if (!this._edge1) {
  54817. this._edge1 = BABYLON.Vector3.Zero();
  54818. this._edge2 = BABYLON.Vector3.Zero();
  54819. this._pvec = BABYLON.Vector3.Zero();
  54820. this._tvec = BABYLON.Vector3.Zero();
  54821. this._qvec = BABYLON.Vector3.Zero();
  54822. }
  54823. vertex1.subtractToRef(vertex0, this._edge1);
  54824. vertex2.subtractToRef(vertex0, this._edge2);
  54825. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54826. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54827. if (det === 0) {
  54828. return null;
  54829. }
  54830. var invdet = 1 / det;
  54831. this.origin.subtractToRef(vertex0, this._tvec);
  54832. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54833. if (bu < 0 || bu > 1.0) {
  54834. return null;
  54835. }
  54836. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54837. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54838. if (bv < 0 || bu + bv > 1.0) {
  54839. return null;
  54840. }
  54841. //check if the distance is longer than the predefined length.
  54842. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54843. if (distance > this.length) {
  54844. return null;
  54845. }
  54846. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54847. };
  54848. Ray.prototype.intersectsPlane = function (plane) {
  54849. var distance;
  54850. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54851. if (Math.abs(result1) < 9.99999997475243E-07) {
  54852. return null;
  54853. }
  54854. else {
  54855. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54856. distance = (-plane.d - result2) / result1;
  54857. if (distance < 0.0) {
  54858. if (distance < -9.99999997475243E-07) {
  54859. return null;
  54860. }
  54861. else {
  54862. return 0;
  54863. }
  54864. }
  54865. return distance;
  54866. }
  54867. };
  54868. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54869. var tm = BABYLON.Tmp.Matrix[0];
  54870. mesh.getWorldMatrix().invertToRef(tm);
  54871. if (this._tmpRay) {
  54872. Ray.TransformToRef(this, tm, this._tmpRay);
  54873. }
  54874. else {
  54875. this._tmpRay = Ray.Transform(this, tm);
  54876. }
  54877. return mesh.intersects(this._tmpRay, fastCheck);
  54878. };
  54879. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54880. if (results) {
  54881. results.length = 0;
  54882. }
  54883. else {
  54884. results = [];
  54885. }
  54886. for (var i = 0; i < meshes.length; i++) {
  54887. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54888. if (pickInfo.hit) {
  54889. results.push(pickInfo);
  54890. }
  54891. }
  54892. results.sort(this._comparePickingInfo);
  54893. return results;
  54894. };
  54895. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54896. if (pickingInfoA.distance < pickingInfoB.distance) {
  54897. return -1;
  54898. }
  54899. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54900. return 1;
  54901. }
  54902. else {
  54903. return 0;
  54904. }
  54905. };
  54906. /**
  54907. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54908. * @param sega the first point of the segment to test the intersection against
  54909. * @param segb the second point of the segment to test the intersection against
  54910. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54911. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54912. */
  54913. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54914. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54915. var u = segb.subtract(sega);
  54916. var v = rsegb.subtract(this.origin);
  54917. var w = sega.subtract(this.origin);
  54918. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54919. var b = BABYLON.Vector3.Dot(u, v);
  54920. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54921. var d = BABYLON.Vector3.Dot(u, w);
  54922. var e = BABYLON.Vector3.Dot(v, w);
  54923. var D = a * c - b * b; // always >= 0
  54924. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54925. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54926. // compute the line parameters of the two closest points
  54927. if (D < Ray.smallnum) { // the lines are almost parallel
  54928. sN = 0.0; // force using point P0 on segment S1
  54929. sD = 1.0; // to prevent possible division by 0.0 later
  54930. tN = e;
  54931. tD = c;
  54932. }
  54933. else { // get the closest points on the infinite lines
  54934. sN = (b * e - c * d);
  54935. tN = (a * e - b * d);
  54936. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54937. sN = 0.0;
  54938. tN = e;
  54939. tD = c;
  54940. }
  54941. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54942. sN = sD;
  54943. tN = e + b;
  54944. tD = c;
  54945. }
  54946. }
  54947. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54948. tN = 0.0;
  54949. // recompute sc for this edge
  54950. if (-d < 0.0) {
  54951. sN = 0.0;
  54952. }
  54953. else if (-d > a)
  54954. sN = sD;
  54955. else {
  54956. sN = -d;
  54957. sD = a;
  54958. }
  54959. }
  54960. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54961. tN = tD;
  54962. // recompute sc for this edge
  54963. if ((-d + b) < 0.0) {
  54964. sN = 0;
  54965. }
  54966. else if ((-d + b) > a) {
  54967. sN = sD;
  54968. }
  54969. else {
  54970. sN = (-d + b);
  54971. sD = a;
  54972. }
  54973. }
  54974. // finally do the division to get sc and tc
  54975. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54976. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54977. // get the difference of the two closest points
  54978. var qtc = v.multiplyByFloats(tc, tc, tc);
  54979. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54980. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54981. if (isIntersected) {
  54982. return qtc.length();
  54983. }
  54984. return -1;
  54985. };
  54986. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54987. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54988. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54989. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54990. this.direction.normalize();
  54991. return this;
  54992. };
  54993. // Statics
  54994. Ray.Zero = function () {
  54995. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54996. };
  54997. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54998. var result = Ray.Zero();
  54999. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55000. };
  55001. /**
  55002. * 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
  55003. * transformed to the given world matrix.
  55004. * @param origin The origin point
  55005. * @param end The end point
  55006. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55007. */
  55008. Ray.CreateNewFromTo = function (origin, end, world) {
  55009. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55010. var direction = end.subtract(origin);
  55011. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55012. direction.normalize();
  55013. return Ray.Transform(new Ray(origin, direction, length), world);
  55014. };
  55015. Ray.Transform = function (ray, matrix) {
  55016. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55017. Ray.TransformToRef(ray, matrix, result);
  55018. return result;
  55019. };
  55020. Ray.TransformToRef = function (ray, matrix, result) {
  55021. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55022. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55023. result.length = ray.length;
  55024. var dir = result.direction;
  55025. var len = dir.length();
  55026. if (!(len === 0 || len === 1)) {
  55027. var num = 1.0 / len;
  55028. dir.x *= num;
  55029. dir.y *= num;
  55030. dir.z *= num;
  55031. result.length *= len;
  55032. }
  55033. };
  55034. Ray.smallnum = 0.00000001;
  55035. Ray.rayl = 10e8;
  55036. return Ray;
  55037. }());
  55038. BABYLON.Ray = Ray;
  55039. })(BABYLON || (BABYLON = {}));
  55040. //# sourceMappingURL=babylon.ray.js.map
  55041. var BABYLON;
  55042. (function (BABYLON) {
  55043. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55044. if (boxMin.x > sphereCenter.x + sphereRadius)
  55045. return false;
  55046. if (sphereCenter.x - sphereRadius > boxMax.x)
  55047. return false;
  55048. if (boxMin.y > sphereCenter.y + sphereRadius)
  55049. return false;
  55050. if (sphereCenter.y - sphereRadius > boxMax.y)
  55051. return false;
  55052. if (boxMin.z > sphereCenter.z + sphereRadius)
  55053. return false;
  55054. if (sphereCenter.z - sphereRadius > boxMax.z)
  55055. return false;
  55056. return true;
  55057. };
  55058. var getLowestRoot = (function () {
  55059. var result = { root: 0, found: false };
  55060. return function (a, b, c, maxR) {
  55061. result.root = 0;
  55062. result.found = false;
  55063. var determinant = b * b - 4.0 * a * c;
  55064. if (determinant < 0)
  55065. return result;
  55066. var sqrtD = Math.sqrt(determinant);
  55067. var r1 = (-b - sqrtD) / (2.0 * a);
  55068. var r2 = (-b + sqrtD) / (2.0 * a);
  55069. if (r1 > r2) {
  55070. var temp = r2;
  55071. r2 = r1;
  55072. r1 = temp;
  55073. }
  55074. if (r1 > 0 && r1 < maxR) {
  55075. result.root = r1;
  55076. result.found = true;
  55077. return result;
  55078. }
  55079. if (r2 > 0 && r2 < maxR) {
  55080. result.root = r2;
  55081. result.found = true;
  55082. return result;
  55083. }
  55084. return result;
  55085. };
  55086. })();
  55087. var Collider = /** @class */ (function () {
  55088. function Collider() {
  55089. this._collisionPoint = BABYLON.Vector3.Zero();
  55090. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55091. this._tempVector = BABYLON.Vector3.Zero();
  55092. this._tempVector2 = BABYLON.Vector3.Zero();
  55093. this._tempVector3 = BABYLON.Vector3.Zero();
  55094. this._tempVector4 = BABYLON.Vector3.Zero();
  55095. this._edge = BABYLON.Vector3.Zero();
  55096. this._baseToVertex = BABYLON.Vector3.Zero();
  55097. this._destinationPoint = BABYLON.Vector3.Zero();
  55098. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55099. this._displacementVector = BABYLON.Vector3.Zero();
  55100. this._radius = BABYLON.Vector3.One();
  55101. this._retry = 0;
  55102. this._basePointWorld = BABYLON.Vector3.Zero();
  55103. this._velocityWorld = BABYLON.Vector3.Zero();
  55104. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55105. this._collisionMask = -1;
  55106. }
  55107. Object.defineProperty(Collider.prototype, "collisionMask", {
  55108. get: function () {
  55109. return this._collisionMask;
  55110. },
  55111. set: function (mask) {
  55112. this._collisionMask = !isNaN(mask) ? mask : -1;
  55113. },
  55114. enumerable: true,
  55115. configurable: true
  55116. });
  55117. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55118. /**
  55119. * Gets the plane normal used to compute the sliding response (in local space)
  55120. */
  55121. get: function () {
  55122. return this._slidePlaneNormal;
  55123. },
  55124. enumerable: true,
  55125. configurable: true
  55126. });
  55127. // Methods
  55128. Collider.prototype._initialize = function (source, dir, e) {
  55129. this._velocity = dir;
  55130. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55131. this._basePoint = source;
  55132. source.multiplyToRef(this._radius, this._basePointWorld);
  55133. dir.multiplyToRef(this._radius, this._velocityWorld);
  55134. this._velocityWorldLength = this._velocityWorld.length();
  55135. this._epsilon = e;
  55136. this.collisionFound = false;
  55137. };
  55138. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55139. pa.subtractToRef(point, this._tempVector);
  55140. pb.subtractToRef(point, this._tempVector2);
  55141. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55142. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55143. if (d < 0)
  55144. return false;
  55145. pc.subtractToRef(point, this._tempVector3);
  55146. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55147. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55148. if (d < 0)
  55149. return false;
  55150. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55151. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55152. return d >= 0;
  55153. };
  55154. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55155. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55156. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55157. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55158. return false;
  55159. }
  55160. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55161. return false;
  55162. return true;
  55163. };
  55164. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55165. var t0;
  55166. var embeddedInPlane = false;
  55167. //defensive programming, actually not needed.
  55168. if (!trianglePlaneArray) {
  55169. trianglePlaneArray = [];
  55170. }
  55171. if (!trianglePlaneArray[faceIndex]) {
  55172. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55173. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55174. }
  55175. var trianglePlane = trianglePlaneArray[faceIndex];
  55176. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55177. return;
  55178. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55179. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55180. if (normalDotVelocity == 0) {
  55181. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55182. return;
  55183. embeddedInPlane = true;
  55184. t0 = 0;
  55185. }
  55186. else {
  55187. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55188. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55189. if (t0 > t1) {
  55190. var temp = t1;
  55191. t1 = t0;
  55192. t0 = temp;
  55193. }
  55194. if (t0 > 1.0 || t1 < 0.0)
  55195. return;
  55196. if (t0 < 0)
  55197. t0 = 0;
  55198. if (t0 > 1.0)
  55199. t0 = 1.0;
  55200. }
  55201. this._collisionPoint.copyFromFloats(0, 0, 0);
  55202. var found = false;
  55203. var t = 1.0;
  55204. if (!embeddedInPlane) {
  55205. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55206. this._velocity.scaleToRef(t0, this._tempVector);
  55207. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55208. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55209. found = true;
  55210. t = t0;
  55211. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55212. }
  55213. }
  55214. if (!found) {
  55215. var velocitySquaredLength = this._velocity.lengthSquared();
  55216. var a = velocitySquaredLength;
  55217. this._basePoint.subtractToRef(p1, this._tempVector);
  55218. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55219. var c = this._tempVector.lengthSquared() - 1.0;
  55220. var lowestRoot = getLowestRoot(a, b, c, t);
  55221. if (lowestRoot.found) {
  55222. t = lowestRoot.root;
  55223. found = true;
  55224. this._collisionPoint.copyFrom(p1);
  55225. }
  55226. this._basePoint.subtractToRef(p2, this._tempVector);
  55227. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55228. c = this._tempVector.lengthSquared() - 1.0;
  55229. lowestRoot = getLowestRoot(a, b, c, t);
  55230. if (lowestRoot.found) {
  55231. t = lowestRoot.root;
  55232. found = true;
  55233. this._collisionPoint.copyFrom(p2);
  55234. }
  55235. this._basePoint.subtractToRef(p3, this._tempVector);
  55236. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55237. c = this._tempVector.lengthSquared() - 1.0;
  55238. lowestRoot = getLowestRoot(a, b, c, t);
  55239. if (lowestRoot.found) {
  55240. t = lowestRoot.root;
  55241. found = true;
  55242. this._collisionPoint.copyFrom(p3);
  55243. }
  55244. p2.subtractToRef(p1, this._edge);
  55245. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55246. var edgeSquaredLength = this._edge.lengthSquared();
  55247. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55248. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55249. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55250. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55251. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55252. lowestRoot = getLowestRoot(a, b, c, t);
  55253. if (lowestRoot.found) {
  55254. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55255. if (f >= 0.0 && f <= 1.0) {
  55256. t = lowestRoot.root;
  55257. found = true;
  55258. this._edge.scaleInPlace(f);
  55259. p1.addToRef(this._edge, this._collisionPoint);
  55260. }
  55261. }
  55262. p3.subtractToRef(p2, this._edge);
  55263. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55264. edgeSquaredLength = this._edge.lengthSquared();
  55265. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55266. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55267. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55268. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55269. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55270. lowestRoot = getLowestRoot(a, b, c, t);
  55271. if (lowestRoot.found) {
  55272. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55273. if (f >= 0.0 && f <= 1.0) {
  55274. t = lowestRoot.root;
  55275. found = true;
  55276. this._edge.scaleInPlace(f);
  55277. p2.addToRef(this._edge, this._collisionPoint);
  55278. }
  55279. }
  55280. p1.subtractToRef(p3, this._edge);
  55281. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55282. edgeSquaredLength = this._edge.lengthSquared();
  55283. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55284. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55285. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55286. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55287. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55288. lowestRoot = getLowestRoot(a, b, c, t);
  55289. if (lowestRoot.found) {
  55290. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55291. if (f >= 0.0 && f <= 1.0) {
  55292. t = lowestRoot.root;
  55293. found = true;
  55294. this._edge.scaleInPlace(f);
  55295. p3.addToRef(this._edge, this._collisionPoint);
  55296. }
  55297. }
  55298. }
  55299. if (found) {
  55300. var distToCollision = t * this._velocity.length();
  55301. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55302. if (!this.intersectionPoint) {
  55303. this.intersectionPoint = this._collisionPoint.clone();
  55304. }
  55305. else {
  55306. this.intersectionPoint.copyFrom(this._collisionPoint);
  55307. }
  55308. this._nearestDistance = distToCollision;
  55309. this.collisionFound = true;
  55310. }
  55311. }
  55312. };
  55313. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55314. for (var i = indexStart; i < indexEnd; i += 3) {
  55315. var p1 = pts[indices[i] - decal];
  55316. var p2 = pts[indices[i + 1] - decal];
  55317. var p3 = pts[indices[i + 2] - decal];
  55318. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55319. }
  55320. };
  55321. Collider.prototype._getResponse = function (pos, vel) {
  55322. pos.addToRef(vel, this._destinationPoint);
  55323. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55324. this._basePoint.addToRef(vel, pos);
  55325. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55326. this._slidePlaneNormal.normalize();
  55327. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55328. pos.addInPlace(this._displacementVector);
  55329. this.intersectionPoint.addInPlace(this._displacementVector);
  55330. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55331. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55332. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55333. };
  55334. return Collider;
  55335. }());
  55336. BABYLON.Collider = Collider;
  55337. })(BABYLON || (BABYLON = {}));
  55338. //# sourceMappingURL=babylon.collider.js.map
  55339. var BABYLON;
  55340. (function (BABYLON) {
  55341. //WebWorker code will be inserted to this variable.
  55342. BABYLON.CollisionWorker = "";
  55343. /** Defines supported task for worker process */
  55344. var WorkerTaskType;
  55345. (function (WorkerTaskType) {
  55346. /** Initialization */
  55347. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55348. /** Update of geometry */
  55349. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55350. /** Evaluate collision */
  55351. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55352. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55353. /** Defines kind of replies returned by worker */
  55354. var WorkerReplyType;
  55355. (function (WorkerReplyType) {
  55356. /** Success */
  55357. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55358. /** Unkown error */
  55359. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55360. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55361. var CollisionCoordinatorWorker = /** @class */ (function () {
  55362. function CollisionCoordinatorWorker() {
  55363. var _this = this;
  55364. this._scaledPosition = BABYLON.Vector3.Zero();
  55365. this._scaledVelocity = BABYLON.Vector3.Zero();
  55366. this.onMeshUpdated = function (transformNode) {
  55367. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55368. };
  55369. this.onGeometryUpdated = function (geometry) {
  55370. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55371. };
  55372. this._afterRender = function () {
  55373. if (!_this._init)
  55374. return;
  55375. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55376. return;
  55377. }
  55378. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55379. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55380. if (_this._runningUpdated > 4) {
  55381. return;
  55382. }
  55383. ++_this._runningUpdated;
  55384. var payload = {
  55385. updatedMeshes: _this._addUpdateMeshesList,
  55386. updatedGeometries: _this._addUpdateGeometriesList,
  55387. removedGeometries: _this._toRemoveGeometryArray,
  55388. removedMeshes: _this._toRemoveMeshesArray
  55389. };
  55390. var message = {
  55391. payload: payload,
  55392. taskType: WorkerTaskType.UPDATE
  55393. };
  55394. var serializable = [];
  55395. for (var id in payload.updatedGeometries) {
  55396. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55397. //prepare transferables
  55398. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55399. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55400. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55401. }
  55402. }
  55403. _this._worker.postMessage(message, serializable);
  55404. _this._addUpdateMeshesList = {};
  55405. _this._addUpdateGeometriesList = {};
  55406. _this._toRemoveGeometryArray = [];
  55407. _this._toRemoveMeshesArray = [];
  55408. };
  55409. this._onMessageFromWorker = function (e) {
  55410. var returnData = e.data;
  55411. if (returnData.error != WorkerReplyType.SUCCESS) {
  55412. //TODO what errors can be returned from the worker?
  55413. BABYLON.Tools.Warn("error returned from worker!");
  55414. return;
  55415. }
  55416. switch (returnData.taskType) {
  55417. case WorkerTaskType.INIT:
  55418. _this._init = true;
  55419. //Update the worked with ALL of the scene's current state
  55420. _this._scene.meshes.forEach(function (mesh) {
  55421. _this.onMeshAdded(mesh);
  55422. });
  55423. _this._scene.getGeometries().forEach(function (geometry) {
  55424. _this.onGeometryAdded(geometry);
  55425. });
  55426. break;
  55427. case WorkerTaskType.UPDATE:
  55428. _this._runningUpdated--;
  55429. break;
  55430. case WorkerTaskType.COLLIDE:
  55431. var returnPayload = returnData.payload;
  55432. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55433. return;
  55434. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55435. if (callback) {
  55436. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55437. if (mesh) {
  55438. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55439. }
  55440. }
  55441. //cleanup
  55442. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55443. break;
  55444. }
  55445. };
  55446. this._collisionsCallbackArray = [];
  55447. this._init = false;
  55448. this._runningUpdated = 0;
  55449. this._addUpdateMeshesList = {};
  55450. this._addUpdateGeometriesList = {};
  55451. this._toRemoveGeometryArray = [];
  55452. this._toRemoveMeshesArray = [];
  55453. }
  55454. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55455. if (!this._init)
  55456. return;
  55457. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55458. return;
  55459. position.divideToRef(collider._radius, this._scaledPosition);
  55460. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55461. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55462. var payload = {
  55463. collider: {
  55464. position: this._scaledPosition.asArray(),
  55465. velocity: this._scaledVelocity.asArray(),
  55466. radius: collider._radius.asArray()
  55467. },
  55468. collisionId: collisionIndex,
  55469. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55470. maximumRetry: maximumRetry
  55471. };
  55472. var message = {
  55473. payload: payload,
  55474. taskType: WorkerTaskType.COLLIDE
  55475. };
  55476. this._worker.postMessage(message);
  55477. };
  55478. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55479. this._scene = scene;
  55480. this._scene.registerAfterRender(this._afterRender);
  55481. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55482. this._worker = new Worker(workerUrl);
  55483. this._worker.onmessage = this._onMessageFromWorker;
  55484. var message = {
  55485. payload: {},
  55486. taskType: WorkerTaskType.INIT
  55487. };
  55488. this._worker.postMessage(message);
  55489. };
  55490. CollisionCoordinatorWorker.prototype.destroy = function () {
  55491. this._scene.unregisterAfterRender(this._afterRender);
  55492. this._worker.terminate();
  55493. };
  55494. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55495. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55496. this.onMeshUpdated(mesh);
  55497. };
  55498. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55499. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55500. };
  55501. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55502. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55503. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55504. this.onGeometryUpdated(geometry);
  55505. };
  55506. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55507. this._toRemoveGeometryArray.push(geometry.id);
  55508. };
  55509. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55510. var submeshes = [];
  55511. if (mesh.subMeshes) {
  55512. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55513. var boundingInfo = sm.getBoundingInfo();
  55514. return {
  55515. position: idx,
  55516. verticesStart: sm.verticesStart,
  55517. verticesCount: sm.verticesCount,
  55518. indexStart: sm.indexStart,
  55519. indexCount: sm.indexCount,
  55520. hasMaterial: !!sm.getMaterial(),
  55521. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55522. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55523. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55524. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55525. };
  55526. });
  55527. }
  55528. var geometryId = null;
  55529. if (mesh instanceof BABYLON.Mesh) {
  55530. var geometry = mesh.geometry;
  55531. geometryId = geometry ? geometry.id : null;
  55532. }
  55533. else if (mesh instanceof BABYLON.InstancedMesh) {
  55534. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55535. geometryId = geometry ? geometry.id : null;
  55536. }
  55537. var boundingInfo = mesh.getBoundingInfo();
  55538. return {
  55539. uniqueId: mesh.uniqueId,
  55540. id: mesh.id,
  55541. name: mesh.name,
  55542. geometryId: geometryId,
  55543. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55544. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55545. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55546. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55547. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55548. subMeshes: submeshes,
  55549. checkCollisions: mesh.checkCollisions
  55550. };
  55551. };
  55552. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55553. return {
  55554. id: geometry.id,
  55555. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55556. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55557. indices: new Uint32Array(geometry.getIndices() || []),
  55558. };
  55559. };
  55560. return CollisionCoordinatorWorker;
  55561. }());
  55562. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55563. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55564. function CollisionCoordinatorLegacy() {
  55565. this._scaledPosition = BABYLON.Vector3.Zero();
  55566. this._scaledVelocity = BABYLON.Vector3.Zero();
  55567. this._finalPosition = BABYLON.Vector3.Zero();
  55568. }
  55569. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55570. position.divideToRef(collider._radius, this._scaledPosition);
  55571. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55572. collider.collidedMesh = null;
  55573. collider._retry = 0;
  55574. collider._initialVelocity = this._scaledVelocity;
  55575. collider._initialPosition = this._scaledPosition;
  55576. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55577. this._finalPosition.multiplyInPlace(collider._radius);
  55578. //run the callback
  55579. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55580. };
  55581. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55582. this._scene = scene;
  55583. };
  55584. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55585. //Legacy need no destruction method.
  55586. };
  55587. //No update in legacy mode
  55588. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55589. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55590. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55591. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55592. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55593. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55594. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55595. if (excludedMesh === void 0) { excludedMesh = null; }
  55596. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55597. if (collider._retry >= maximumRetry) {
  55598. finalPosition.copyFrom(position);
  55599. return;
  55600. }
  55601. // Check if this is a mesh else camera or -1
  55602. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55603. collider._initialize(position, velocity, closeDistance);
  55604. // Check all meshes
  55605. for (var index = 0; index < this._scene.meshes.length; index++) {
  55606. var mesh = this._scene.meshes[index];
  55607. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55608. mesh._checkCollision(collider);
  55609. }
  55610. }
  55611. if (!collider.collisionFound) {
  55612. position.addToRef(velocity, finalPosition);
  55613. return;
  55614. }
  55615. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55616. collider._getResponse(position, velocity);
  55617. }
  55618. if (velocity.length() <= closeDistance) {
  55619. finalPosition.copyFrom(position);
  55620. return;
  55621. }
  55622. collider._retry++;
  55623. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55624. };
  55625. return CollisionCoordinatorLegacy;
  55626. }());
  55627. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55628. })(BABYLON || (BABYLON = {}));
  55629. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55630. var BABYLON;
  55631. (function (BABYLON) {
  55632. /**
  55633. * A particle represents one of the element emitted by a particle system.
  55634. * This is mainly define by its coordinates, direction, velocity and age.
  55635. */
  55636. var Particle = /** @class */ (function () {
  55637. /**
  55638. * Creates a new instance Particle
  55639. * @param particleSystem the particle system the particle belongs to
  55640. */
  55641. function Particle(
  55642. /**
  55643. * particleSystem the particle system the particle belongs to.
  55644. */
  55645. particleSystem) {
  55646. this.particleSystem = particleSystem;
  55647. /**
  55648. * The world position of the particle in the scene.
  55649. */
  55650. this.position = BABYLON.Vector3.Zero();
  55651. /**
  55652. * The world direction of the particle in the scene.
  55653. */
  55654. this.direction = BABYLON.Vector3.Zero();
  55655. /**
  55656. * The color of the particle.
  55657. */
  55658. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55659. /**
  55660. * The color change of the particle per step.
  55661. */
  55662. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55663. /**
  55664. * Defines how long will the life of the particle be.
  55665. */
  55666. this.lifeTime = 1.0;
  55667. /**
  55668. * The current age of the particle.
  55669. */
  55670. this.age = 0;
  55671. /**
  55672. * The current size of the particle.
  55673. */
  55674. this.size = 0;
  55675. /**
  55676. * The current angle of the particle.
  55677. */
  55678. this.angle = 0;
  55679. /**
  55680. * Defines how fast is the angle changing.
  55681. */
  55682. this.angularSpeed = 0;
  55683. /**
  55684. * Defines the cell index used by the particle to be rendered from a sprite.
  55685. */
  55686. this.cellIndex = 0;
  55687. this._currentFrameCounter = 0;
  55688. if (!this.particleSystem.isAnimationSheetEnabled) {
  55689. return;
  55690. }
  55691. this.updateCellInfoFromSystem();
  55692. }
  55693. Particle.prototype.updateCellInfoFromSystem = function () {
  55694. this.cellIndex = this.particleSystem.startSpriteCellID;
  55695. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55696. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55697. }
  55698. else {
  55699. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55700. }
  55701. };
  55702. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55703. // (ageOffset / scaledUpdateSpeed) / available cells
  55704. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55705. this._currentFrameCounter += scaledUpdateSpeed;
  55706. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55707. this._currentFrameCounter = 0;
  55708. this.cellIndex++;
  55709. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55710. this.cellIndex = this.particleSystem.endSpriteCellID;
  55711. }
  55712. }
  55713. };
  55714. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55715. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55716. this.cellIndex++;
  55717. this._currentFrameCounter = 0;
  55718. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55719. if (this.particleSystem.spriteCellLoop) {
  55720. this.cellIndex = this.particleSystem.startSpriteCellID;
  55721. }
  55722. else {
  55723. this.cellIndex = this.particleSystem.endSpriteCellID;
  55724. }
  55725. }
  55726. }
  55727. else {
  55728. this._currentFrameCounter++;
  55729. }
  55730. };
  55731. /**
  55732. * Copy the properties of particle to another one.
  55733. * @param other the particle to copy the information to.
  55734. */
  55735. Particle.prototype.copyTo = function (other) {
  55736. other.position.copyFrom(this.position);
  55737. other.direction.copyFrom(this.direction);
  55738. other.color.copyFrom(this.color);
  55739. other.colorStep.copyFrom(this.colorStep);
  55740. other.lifeTime = this.lifeTime;
  55741. other.age = this.age;
  55742. other.size = this.size;
  55743. other.angle = this.angle;
  55744. other.angularSpeed = this.angularSpeed;
  55745. other.particleSystem = this.particleSystem;
  55746. other.cellIndex = this.cellIndex;
  55747. };
  55748. return Particle;
  55749. }());
  55750. BABYLON.Particle = Particle;
  55751. })(BABYLON || (BABYLON = {}));
  55752. //# sourceMappingURL=babylon.particle.js.map
  55753. var BABYLON;
  55754. (function (BABYLON) {
  55755. /**
  55756. * This represents a particle system in Babylon.
  55757. * 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.
  55758. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55759. * @example https://doc.babylonjs.com/babylon101/particles
  55760. */
  55761. var ParticleSystem = /** @class */ (function () {
  55762. /**
  55763. * Instantiates a particle system.
  55764. * 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.
  55765. * @param name The name of the particle system
  55766. * @param capacity The max number of particles alive at the same time
  55767. * @param scene The scene the particle system belongs to
  55768. * @param customEffect a custom effect used to change the way particles are rendered by default
  55769. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55770. * @param epsilon Offset used to render the particles
  55771. */
  55772. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55773. if (customEffect === void 0) { customEffect = null; }
  55774. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55775. if (epsilon === void 0) { epsilon = 0.01; }
  55776. var _this = this;
  55777. /**
  55778. * List of animations used by the particle system.
  55779. */
  55780. this.animations = [];
  55781. /**
  55782. * The rendering group used by the Particle system to chose when to render.
  55783. */
  55784. this.renderingGroupId = 0;
  55785. /**
  55786. * The emitter represents the Mesh or position we are attaching the particle system to.
  55787. */
  55788. this.emitter = null;
  55789. /**
  55790. * The maximum number of particles to emit per frame
  55791. */
  55792. this.emitRate = 10;
  55793. /**
  55794. * If you want to launch only a few particles at once, that can be done, as well.
  55795. */
  55796. this.manualEmitCount = -1;
  55797. /**
  55798. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55799. */
  55800. this.updateSpeed = 0.01;
  55801. /**
  55802. * The amount of time the particle system is running (depends of the overall update speed).
  55803. */
  55804. this.targetStopDuration = 0;
  55805. /**
  55806. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55807. */
  55808. this.disposeOnStop = false;
  55809. /**
  55810. * Minimum power of emitting particles.
  55811. */
  55812. this.minEmitPower = 1;
  55813. /**
  55814. * Maximum power of emitting particles.
  55815. */
  55816. this.maxEmitPower = 1;
  55817. /**
  55818. * Minimum life time of emitting particles.
  55819. */
  55820. this.minLifeTime = 1;
  55821. /**
  55822. * Maximum life time of emitting particles.
  55823. */
  55824. this.maxLifeTime = 1;
  55825. /**
  55826. * Minimum Size of emitting particles.
  55827. */
  55828. this.minSize = 1;
  55829. /**
  55830. * Maximum Size of emitting particles.
  55831. */
  55832. this.maxSize = 1;
  55833. /**
  55834. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55835. */
  55836. this.minAngularSpeed = 0;
  55837. /**
  55838. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55839. */
  55840. this.maxAngularSpeed = 0;
  55841. /**
  55842. * The layer mask we are rendering the particles through.
  55843. */
  55844. this.layerMask = 0x0FFFFFFF;
  55845. /**
  55846. * This can help using your own shader to render the particle system.
  55847. * The according effect will be created
  55848. */
  55849. this.customShader = null;
  55850. /**
  55851. * By default particle system starts as soon as they are created. This prevents the
  55852. * automatic start to happen and let you decide when to start emitting particles.
  55853. */
  55854. this.preventAutoStart = false;
  55855. /**
  55856. * Callback triggered when the particle animation is ending.
  55857. */
  55858. this.onAnimationEnd = null;
  55859. /**
  55860. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55861. */
  55862. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55863. /**
  55864. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55865. * to override the particles.
  55866. */
  55867. this.forceDepthWrite = false;
  55868. /**
  55869. * You can use gravity if you want to give an orientation to your particles.
  55870. */
  55871. this.gravity = BABYLON.Vector3.Zero();
  55872. /**
  55873. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55874. */
  55875. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55876. /**
  55877. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55878. */
  55879. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55880. /**
  55881. * Color the particle will have at the end of its lifetime.
  55882. */
  55883. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55884. /**
  55885. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55886. */
  55887. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55888. /**
  55889. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55890. */
  55891. this.spriteCellLoop = true;
  55892. /**
  55893. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55894. */
  55895. this.spriteCellChangeSpeed = 0;
  55896. /**
  55897. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55898. */
  55899. this.startSpriteCellID = 0;
  55900. /**
  55901. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55902. */
  55903. this.endSpriteCellID = 0;
  55904. /**
  55905. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55906. */
  55907. this.spriteCellWidth = 0;
  55908. /**
  55909. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55910. */
  55911. this.spriteCellHeight = 0;
  55912. /**
  55913. * An event triggered when the system is disposed.
  55914. */
  55915. this.onDisposeObservable = new BABYLON.Observable();
  55916. this._particles = new Array();
  55917. this._stockParticles = new Array();
  55918. this._newPartsExcess = 0;
  55919. this._vertexBuffers = {};
  55920. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55921. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55922. this._scaledDirection = BABYLON.Vector3.Zero();
  55923. this._scaledGravity = BABYLON.Vector3.Zero();
  55924. this._currentRenderId = -1;
  55925. this._started = false;
  55926. this._stopped = false;
  55927. this._actualFrame = 0;
  55928. this._vertexBufferSize = 11;
  55929. // start of sub system methods
  55930. /**
  55931. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55932. * Its lifetime will start back at 0.
  55933. */
  55934. this.recycleParticle = function (particle) {
  55935. var lastParticle = _this._particles.pop();
  55936. if (lastParticle !== particle) {
  55937. lastParticle.copyTo(particle);
  55938. }
  55939. _this._stockParticles.push(lastParticle);
  55940. };
  55941. this._createParticle = function () {
  55942. var particle;
  55943. if (_this._stockParticles.length !== 0) {
  55944. particle = _this._stockParticles.pop();
  55945. particle.age = 0;
  55946. particle.cellIndex = _this.startSpriteCellID;
  55947. }
  55948. else {
  55949. particle = new BABYLON.Particle(_this);
  55950. }
  55951. return particle;
  55952. };
  55953. this._emitFromParticle = function (particle) {
  55954. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55955. return;
  55956. }
  55957. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55958. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55959. subSystem._rootParticleSystem = _this;
  55960. _this.activeSubSystems.push(subSystem);
  55961. subSystem.start();
  55962. };
  55963. this._appendParticleVertexes = null;
  55964. this.id = name;
  55965. this.name = name;
  55966. this._capacity = capacity;
  55967. this._epsilon = epsilon;
  55968. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55969. if (isAnimationSheetEnabled) {
  55970. this._vertexBufferSize = 12;
  55971. }
  55972. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55973. this._customEffect = customEffect;
  55974. scene.particleSystems.push(this);
  55975. this._createIndexBuffer();
  55976. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55977. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55978. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55979. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55980. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55981. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55982. if (this._isAnimationSheetEnabled) {
  55983. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55984. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55985. }
  55986. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55987. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55988. this._vertexBuffers["options"] = options;
  55989. // Default emitter type
  55990. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55991. this.updateFunction = function (particles) {
  55992. for (var index = 0; index < particles.length; index++) {
  55993. var particle = particles[index];
  55994. particle.age += _this._scaledUpdateSpeed;
  55995. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55996. _this._emitFromParticle(particle);
  55997. _this.recycleParticle(particle);
  55998. index--;
  55999. continue;
  56000. }
  56001. else {
  56002. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56003. particle.color.addInPlace(_this._scaledColorStep);
  56004. if (particle.color.a < 0)
  56005. particle.color.a = 0;
  56006. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56007. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56008. particle.position.addInPlace(_this._scaledDirection);
  56009. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56010. particle.direction.addInPlace(_this._scaledGravity);
  56011. if (_this._isAnimationSheetEnabled) {
  56012. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56013. }
  56014. }
  56015. }
  56016. };
  56017. }
  56018. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56019. /**
  56020. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56021. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56022. */
  56023. get: function () {
  56024. if (this.particleEmitterType.direction1) {
  56025. return this.particleEmitterType.direction1;
  56026. }
  56027. return BABYLON.Vector3.Zero();
  56028. },
  56029. set: function (value) {
  56030. if (this.particleEmitterType.direction1) {
  56031. this.particleEmitterType.direction1 = value;
  56032. }
  56033. },
  56034. enumerable: true,
  56035. configurable: true
  56036. });
  56037. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56038. /**
  56039. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56040. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56041. */
  56042. get: function () {
  56043. if (this.particleEmitterType.direction2) {
  56044. return this.particleEmitterType.direction2;
  56045. }
  56046. return BABYLON.Vector3.Zero();
  56047. },
  56048. set: function (value) {
  56049. if (this.particleEmitterType.direction2) {
  56050. this.particleEmitterType.direction2 = value;
  56051. }
  56052. },
  56053. enumerable: true,
  56054. configurable: true
  56055. });
  56056. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56057. /**
  56058. * 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.
  56059. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56060. */
  56061. get: function () {
  56062. if (this.particleEmitterType.minEmitBox) {
  56063. return this.particleEmitterType.minEmitBox;
  56064. }
  56065. return BABYLON.Vector3.Zero();
  56066. },
  56067. set: function (value) {
  56068. if (this.particleEmitterType.minEmitBox) {
  56069. this.particleEmitterType.minEmitBox = value;
  56070. }
  56071. },
  56072. enumerable: true,
  56073. configurable: true
  56074. });
  56075. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56076. /**
  56077. * 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.
  56078. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56079. */
  56080. get: function () {
  56081. if (this.particleEmitterType.maxEmitBox) {
  56082. return this.particleEmitterType.maxEmitBox;
  56083. }
  56084. return BABYLON.Vector3.Zero();
  56085. },
  56086. set: function (value) {
  56087. if (this.particleEmitterType.maxEmitBox) {
  56088. this.particleEmitterType.maxEmitBox = value;
  56089. }
  56090. },
  56091. enumerable: true,
  56092. configurable: true
  56093. });
  56094. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56095. /**
  56096. * Sets a callback that will be triggered when the system is disposed.
  56097. */
  56098. set: function (callback) {
  56099. if (this._onDisposeObserver) {
  56100. this.onDisposeObservable.remove(this._onDisposeObserver);
  56101. }
  56102. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56103. },
  56104. enumerable: true,
  56105. configurable: true
  56106. });
  56107. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56108. /**
  56109. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56110. */
  56111. get: function () {
  56112. return this._isAnimationSheetEnabled;
  56113. },
  56114. enumerable: true,
  56115. configurable: true
  56116. });
  56117. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56118. //end of Sub-emitter
  56119. /**
  56120. * Gets the current list of active particles
  56121. */
  56122. get: function () {
  56123. return this._particles;
  56124. },
  56125. enumerable: true,
  56126. configurable: true
  56127. });
  56128. /**
  56129. * Returns the string "ParticleSystem"
  56130. * @returns a string containing the class name
  56131. */
  56132. ParticleSystem.prototype.getClassName = function () {
  56133. return "ParticleSystem";
  56134. };
  56135. ParticleSystem.prototype._createIndexBuffer = function () {
  56136. var indices = [];
  56137. var index = 0;
  56138. for (var count = 0; count < this._capacity; count++) {
  56139. indices.push(index);
  56140. indices.push(index + 1);
  56141. indices.push(index + 2);
  56142. indices.push(index);
  56143. indices.push(index + 2);
  56144. indices.push(index + 3);
  56145. index += 4;
  56146. }
  56147. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56148. };
  56149. /**
  56150. * Gets the maximum number of particles active at the same time.
  56151. * @returns The max number of active particles.
  56152. */
  56153. ParticleSystem.prototype.getCapacity = function () {
  56154. return this._capacity;
  56155. };
  56156. /**
  56157. * Gets Wether there are still active particles in the system.
  56158. * @returns True if it is alive, otherwise false.
  56159. */
  56160. ParticleSystem.prototype.isAlive = function () {
  56161. return this._alive;
  56162. };
  56163. /**
  56164. * Gets Wether the system has been started.
  56165. * @returns True if it has been started, otherwise false.
  56166. */
  56167. ParticleSystem.prototype.isStarted = function () {
  56168. return this._started;
  56169. };
  56170. /**
  56171. * Starts the particle system and begins to emit.
  56172. */
  56173. ParticleSystem.prototype.start = function () {
  56174. this._started = true;
  56175. this._stopped = false;
  56176. this._actualFrame = 0;
  56177. if (this.subEmitters && this.subEmitters.length != 0) {
  56178. this.activeSubSystems = new Array();
  56179. }
  56180. };
  56181. /**
  56182. * Stops the particle system.
  56183. * @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.
  56184. */
  56185. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56186. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56187. this._stopped = true;
  56188. if (stopSubEmitters) {
  56189. this._stopSubEmitters();
  56190. }
  56191. };
  56192. // animation sheet
  56193. /**
  56194. * Remove all active particles
  56195. */
  56196. ParticleSystem.prototype.reset = function () {
  56197. this._stockParticles = [];
  56198. this._particles = [];
  56199. };
  56200. /**
  56201. * @hidden (for internal use only)
  56202. */
  56203. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56204. var offset = index * this._vertexBufferSize;
  56205. this._vertexData[offset] = particle.position.x;
  56206. this._vertexData[offset + 1] = particle.position.y;
  56207. this._vertexData[offset + 2] = particle.position.z;
  56208. this._vertexData[offset + 3] = particle.color.r;
  56209. this._vertexData[offset + 4] = particle.color.g;
  56210. this._vertexData[offset + 5] = particle.color.b;
  56211. this._vertexData[offset + 6] = particle.color.a;
  56212. this._vertexData[offset + 7] = particle.angle;
  56213. this._vertexData[offset + 8] = particle.size;
  56214. this._vertexData[offset + 9] = offsetX;
  56215. this._vertexData[offset + 10] = offsetY;
  56216. };
  56217. /**
  56218. * @hidden (for internal use only)
  56219. */
  56220. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56221. if (offsetX === 0)
  56222. offsetX = this._epsilon;
  56223. else if (offsetX === 1)
  56224. offsetX = 1 - this._epsilon;
  56225. if (offsetY === 0)
  56226. offsetY = this._epsilon;
  56227. else if (offsetY === 1)
  56228. offsetY = 1 - this._epsilon;
  56229. var offset = index * this._vertexBufferSize;
  56230. this._vertexData[offset] = particle.position.x;
  56231. this._vertexData[offset + 1] = particle.position.y;
  56232. this._vertexData[offset + 2] = particle.position.z;
  56233. this._vertexData[offset + 3] = particle.color.r;
  56234. this._vertexData[offset + 4] = particle.color.g;
  56235. this._vertexData[offset + 5] = particle.color.b;
  56236. this._vertexData[offset + 6] = particle.color.a;
  56237. this._vertexData[offset + 7] = particle.angle;
  56238. this._vertexData[offset + 8] = particle.size;
  56239. this._vertexData[offset + 9] = offsetX;
  56240. this._vertexData[offset + 10] = offsetY;
  56241. this._vertexData[offset + 11] = particle.cellIndex;
  56242. };
  56243. ParticleSystem.prototype._stopSubEmitters = function () {
  56244. if (!this.activeSubSystems) {
  56245. return;
  56246. }
  56247. this.activeSubSystems.forEach(function (subSystem) {
  56248. subSystem.stop(true);
  56249. });
  56250. this.activeSubSystems = new Array();
  56251. };
  56252. ParticleSystem.prototype._removeFromRoot = function () {
  56253. if (!this._rootParticleSystem) {
  56254. return;
  56255. }
  56256. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56257. if (index !== -1) {
  56258. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56259. }
  56260. };
  56261. // end of sub system methods
  56262. ParticleSystem.prototype._update = function (newParticles) {
  56263. // Update current
  56264. this._alive = this._particles.length > 0;
  56265. this.updateFunction(this._particles);
  56266. // Add new ones
  56267. var worldMatrix;
  56268. if (this.emitter.position) {
  56269. var emitterMesh = this.emitter;
  56270. worldMatrix = emitterMesh.getWorldMatrix();
  56271. }
  56272. else {
  56273. var emitterPosition = this.emitter;
  56274. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56275. }
  56276. var particle;
  56277. for (var index = 0; index < newParticles; index++) {
  56278. if (this._particles.length === this._capacity) {
  56279. break;
  56280. }
  56281. particle = this._createParticle();
  56282. this._particles.push(particle);
  56283. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56284. if (this.startPositionFunction) {
  56285. this.startPositionFunction(worldMatrix, particle.position, particle);
  56286. }
  56287. else {
  56288. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56289. }
  56290. if (this.startDirectionFunction) {
  56291. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56292. }
  56293. else {
  56294. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56295. }
  56296. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56297. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56298. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56299. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56300. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56301. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56302. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56303. }
  56304. };
  56305. ParticleSystem.prototype._getEffect = function () {
  56306. if (this._customEffect) {
  56307. return this._customEffect;
  56308. }
  56309. ;
  56310. var defines = [];
  56311. if (this._scene.clipPlane) {
  56312. defines.push("#define CLIPPLANE");
  56313. }
  56314. if (this._isAnimationSheetEnabled) {
  56315. defines.push("#define ANIMATESHEET");
  56316. }
  56317. // Effect
  56318. var join = defines.join("\n");
  56319. if (this._cachedDefines !== join) {
  56320. this._cachedDefines = join;
  56321. var attributesNamesOrOptions;
  56322. var effectCreationOption;
  56323. if (this._isAnimationSheetEnabled) {
  56324. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56325. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56326. }
  56327. else {
  56328. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56329. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56330. }
  56331. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56332. }
  56333. return this._effect;
  56334. };
  56335. /**
  56336. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56337. */
  56338. ParticleSystem.prototype.animate = function () {
  56339. if (!this._started)
  56340. return;
  56341. var effect = this._getEffect();
  56342. // Check
  56343. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56344. return;
  56345. if (this._currentRenderId === this._scene.getRenderId()) {
  56346. return;
  56347. }
  56348. this._currentRenderId = this._scene.getRenderId();
  56349. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56350. // determine the number of particles we need to create
  56351. var newParticles;
  56352. if (this.manualEmitCount > -1) {
  56353. newParticles = this.manualEmitCount;
  56354. this._newPartsExcess = 0;
  56355. this.manualEmitCount = 0;
  56356. }
  56357. else {
  56358. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56359. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56360. }
  56361. if (this._newPartsExcess > 1.0) {
  56362. newParticles += this._newPartsExcess >> 0;
  56363. this._newPartsExcess -= this._newPartsExcess >> 0;
  56364. }
  56365. this._alive = false;
  56366. if (!this._stopped) {
  56367. this._actualFrame += this._scaledUpdateSpeed;
  56368. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56369. this.stop();
  56370. }
  56371. else {
  56372. newParticles = 0;
  56373. }
  56374. this._update(newParticles);
  56375. // Stopped?
  56376. if (this._stopped) {
  56377. if (!this._alive) {
  56378. this._started = false;
  56379. if (this.onAnimationEnd) {
  56380. this.onAnimationEnd();
  56381. }
  56382. if (this.disposeOnStop) {
  56383. this._scene._toBeDisposed.push(this);
  56384. }
  56385. }
  56386. }
  56387. // Animation sheet
  56388. if (this._isAnimationSheetEnabled) {
  56389. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56390. }
  56391. else {
  56392. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56393. }
  56394. // Update VBO
  56395. var offset = 0;
  56396. for (var index = 0; index < this._particles.length; index++) {
  56397. var particle = this._particles[index];
  56398. this._appendParticleVertexes(offset, particle);
  56399. offset += 4;
  56400. }
  56401. if (this._vertexBuffer) {
  56402. this._vertexBuffer.update(this._vertexData);
  56403. }
  56404. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56405. this.stop();
  56406. }
  56407. };
  56408. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56409. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56410. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56411. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56412. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56413. };
  56414. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56415. this._appendParticleVertex(offset++, particle, 0, 0);
  56416. this._appendParticleVertex(offset++, particle, 1, 0);
  56417. this._appendParticleVertex(offset++, particle, 1, 1);
  56418. this._appendParticleVertex(offset++, particle, 0, 1);
  56419. };
  56420. /**
  56421. * Rebuilds the particle system.
  56422. */
  56423. ParticleSystem.prototype.rebuild = function () {
  56424. this._createIndexBuffer();
  56425. if (this._vertexBuffer) {
  56426. this._vertexBuffer._rebuild();
  56427. }
  56428. };
  56429. /**
  56430. * Is this system ready to be used/rendered
  56431. * @return true if the system is ready
  56432. */
  56433. ParticleSystem.prototype.isReady = function () {
  56434. var effect = this._getEffect();
  56435. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56436. return false;
  56437. }
  56438. return true;
  56439. };
  56440. /**
  56441. * Renders the particle system in its current state.
  56442. * @returns the current number of particles
  56443. */
  56444. ParticleSystem.prototype.render = function () {
  56445. var effect = this._getEffect();
  56446. // Check
  56447. if (!this.isReady() || !this._particles.length) {
  56448. return 0;
  56449. }
  56450. var engine = this._scene.getEngine();
  56451. // Render
  56452. engine.enableEffect(effect);
  56453. engine.setState(false);
  56454. var viewMatrix = this._scene.getViewMatrix();
  56455. effect.setTexture("diffuseSampler", this.particleTexture);
  56456. effect.setMatrix("view", viewMatrix);
  56457. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56458. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56459. var baseSize = this.particleTexture.getBaseSize();
  56460. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56461. }
  56462. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56463. if (this._scene.clipPlane) {
  56464. var clipPlane = this._scene.clipPlane;
  56465. var invView = viewMatrix.clone();
  56466. invView.invert();
  56467. effect.setMatrix("invView", invView);
  56468. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56469. }
  56470. // VBOs
  56471. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56472. // Draw order
  56473. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56474. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56475. }
  56476. else {
  56477. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56478. }
  56479. if (this.forceDepthWrite) {
  56480. engine.setDepthWrite(true);
  56481. }
  56482. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56483. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56484. return this._particles.length;
  56485. };
  56486. /**
  56487. * Disposes the particle system and free the associated resources
  56488. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56489. */
  56490. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56491. if (disposeTexture === void 0) { disposeTexture = true; }
  56492. if (this._vertexBuffer) {
  56493. this._vertexBuffer.dispose();
  56494. this._vertexBuffer = null;
  56495. }
  56496. if (this._indexBuffer) {
  56497. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56498. this._indexBuffer = null;
  56499. }
  56500. if (disposeTexture && this.particleTexture) {
  56501. this.particleTexture.dispose();
  56502. this.particleTexture = null;
  56503. }
  56504. this._removeFromRoot();
  56505. // Remove from scene
  56506. var index = this._scene.particleSystems.indexOf(this);
  56507. if (index > -1) {
  56508. this._scene.particleSystems.splice(index, 1);
  56509. }
  56510. // Callback
  56511. this.onDisposeObservable.notifyObservers(this);
  56512. this.onDisposeObservable.clear();
  56513. };
  56514. /**
  56515. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56516. * @param radius The radius of the sphere to emit from
  56517. * @returns the emitter
  56518. */
  56519. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56520. if (radius === void 0) { radius = 1; }
  56521. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56522. this.particleEmitterType = particleEmitter;
  56523. return particleEmitter;
  56524. };
  56525. /**
  56526. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56527. * @param radius The radius of the sphere to emit from
  56528. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56529. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56530. * @returns the emitter
  56531. */
  56532. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56533. if (radius === void 0) { radius = 1; }
  56534. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56535. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56536. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56537. this.particleEmitterType = particleEmitter;
  56538. return particleEmitter;
  56539. };
  56540. /**
  56541. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56542. * @param radius The radius of the cone to emit from
  56543. * @param angle The base angle of the cone
  56544. * @returns the emitter
  56545. */
  56546. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56547. if (radius === void 0) { radius = 1; }
  56548. if (angle === void 0) { angle = Math.PI / 4; }
  56549. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56550. this.particleEmitterType = particleEmitter;
  56551. return particleEmitter;
  56552. };
  56553. // 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.
  56554. /**
  56555. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56556. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56557. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56558. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56559. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56560. * @returns the emitter
  56561. */
  56562. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56563. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56564. this.particleEmitterType = particleEmitter;
  56565. this.direction1 = direction1;
  56566. this.direction2 = direction2;
  56567. this.minEmitBox = minEmitBox;
  56568. this.maxEmitBox = maxEmitBox;
  56569. return particleEmitter;
  56570. };
  56571. // Clone
  56572. /**
  56573. * Clones the particle system.
  56574. * @param name The name of the cloned object
  56575. * @param newEmitter The new emitter to use
  56576. * @returns the cloned particle system
  56577. */
  56578. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56579. var custom = null;
  56580. var program = null;
  56581. if (this.customShader != null) {
  56582. program = this.customShader;
  56583. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56584. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56585. }
  56586. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56587. result.customShader = program;
  56588. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56589. if (newEmitter === undefined) {
  56590. newEmitter = this.emitter;
  56591. }
  56592. result.emitter = newEmitter;
  56593. if (this.particleTexture) {
  56594. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56595. }
  56596. if (!this.preventAutoStart) {
  56597. result.start();
  56598. }
  56599. return result;
  56600. };
  56601. /**
  56602. * Serializes the particle system to a JSON object.
  56603. * @returns the JSON object
  56604. */
  56605. ParticleSystem.prototype.serialize = function () {
  56606. var serializationObject = {};
  56607. serializationObject.name = this.name;
  56608. serializationObject.id = this.id;
  56609. // Emitter
  56610. if (this.emitter.position) {
  56611. var emitterMesh = this.emitter;
  56612. serializationObject.emitterId = emitterMesh.id;
  56613. }
  56614. else {
  56615. var emitterPosition = this.emitter;
  56616. serializationObject.emitter = emitterPosition.asArray();
  56617. }
  56618. serializationObject.capacity = this.getCapacity();
  56619. if (this.particleTexture) {
  56620. serializationObject.textureName = this.particleTexture.name;
  56621. }
  56622. // Animations
  56623. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56624. // Particle system
  56625. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56626. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56627. serializationObject.minSize = this.minSize;
  56628. serializationObject.maxSize = this.maxSize;
  56629. serializationObject.minEmitPower = this.minEmitPower;
  56630. serializationObject.maxEmitPower = this.maxEmitPower;
  56631. serializationObject.minLifeTime = this.minLifeTime;
  56632. serializationObject.maxLifeTime = this.maxLifeTime;
  56633. serializationObject.emitRate = this.emitRate;
  56634. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56635. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56636. serializationObject.gravity = this.gravity.asArray();
  56637. serializationObject.direction1 = this.direction1.asArray();
  56638. serializationObject.direction2 = this.direction2.asArray();
  56639. serializationObject.color1 = this.color1.asArray();
  56640. serializationObject.color2 = this.color2.asArray();
  56641. serializationObject.colorDead = this.colorDead.asArray();
  56642. serializationObject.updateSpeed = this.updateSpeed;
  56643. serializationObject.targetStopDuration = this.targetStopDuration;
  56644. serializationObject.textureMask = this.textureMask.asArray();
  56645. serializationObject.blendMode = this.blendMode;
  56646. serializationObject.customShader = this.customShader;
  56647. serializationObject.preventAutoStart = this.preventAutoStart;
  56648. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56649. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56650. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56651. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56652. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56653. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56654. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56655. // Emitter
  56656. if (this.particleEmitterType) {
  56657. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56658. }
  56659. return serializationObject;
  56660. };
  56661. /**
  56662. * Parses a JSON object to create a particle system.
  56663. * @param parsedParticleSystem The JSON object to parse
  56664. * @param scene The scene to create the particle system in
  56665. * @param rootUrl The root url to use to load external dependencies like texture
  56666. * @returns the Parsed particle system
  56667. */
  56668. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56669. var name = parsedParticleSystem.name;
  56670. var custom = null;
  56671. var program = null;
  56672. if (parsedParticleSystem.customShader) {
  56673. program = parsedParticleSystem.customShader;
  56674. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56675. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56676. }
  56677. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56678. particleSystem.customShader = program;
  56679. if (parsedParticleSystem.id) {
  56680. particleSystem.id = parsedParticleSystem.id;
  56681. }
  56682. // Auto start
  56683. if (parsedParticleSystem.preventAutoStart) {
  56684. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56685. }
  56686. // Texture
  56687. if (parsedParticleSystem.textureName) {
  56688. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56689. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56690. }
  56691. // Emitter
  56692. if (parsedParticleSystem.emitterId) {
  56693. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56694. }
  56695. else {
  56696. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56697. }
  56698. // Animations
  56699. if (parsedParticleSystem.animations) {
  56700. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56701. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56702. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56703. }
  56704. }
  56705. if (parsedParticleSystem.autoAnimate) {
  56706. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56707. }
  56708. // Particle system
  56709. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56710. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56711. particleSystem.minSize = parsedParticleSystem.minSize;
  56712. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56713. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56714. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56715. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56716. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56717. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56718. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56719. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56720. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56721. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56722. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56723. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56724. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56725. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56726. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56727. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56728. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56729. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56730. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56731. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56732. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56733. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56734. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56735. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56736. if (!particleSystem.preventAutoStart) {
  56737. particleSystem.start();
  56738. }
  56739. return particleSystem;
  56740. };
  56741. /**
  56742. * Source color is added to the destination color without alpha affecting the result.
  56743. */
  56744. ParticleSystem.BLENDMODE_ONEONE = 0;
  56745. /**
  56746. * Blend current color and particle color using particle’s alpha.
  56747. */
  56748. ParticleSystem.BLENDMODE_STANDARD = 1;
  56749. return ParticleSystem;
  56750. }());
  56751. BABYLON.ParticleSystem = ParticleSystem;
  56752. })(BABYLON || (BABYLON = {}));
  56753. //# sourceMappingURL=babylon.particleSystem.js.map
  56754. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56755. var BABYLON;
  56756. (function (BABYLON) {
  56757. /**
  56758. * Particle emitter emitting particles from the inside of a box.
  56759. * It emits the particles randomly between 2 given directions.
  56760. */
  56761. var BoxParticleEmitter = /** @class */ (function () {
  56762. /**
  56763. * Creates a new instance BoxParticleEmitter
  56764. */
  56765. function BoxParticleEmitter() {
  56766. /**
  56767. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56768. */
  56769. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56770. /**
  56771. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56772. */
  56773. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56774. /**
  56775. * 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.
  56776. */
  56777. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56778. /**
  56779. * 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.
  56780. */
  56781. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56782. }
  56783. /**
  56784. * Called by the particle System when the direction is computed for the created particle.
  56785. * @param emitPower is the power of the particle (speed)
  56786. * @param worldMatrix is the world matrix of the particle system
  56787. * @param directionToUpdate is the direction vector to update with the result
  56788. * @param particle is the particle we are computed the direction for
  56789. */
  56790. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56791. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56792. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56793. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56794. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56795. };
  56796. /**
  56797. * Called by the particle System when the position is computed for the created particle.
  56798. * @param worldMatrix is the world matrix of the particle system
  56799. * @param positionToUpdate is the position vector to update with the result
  56800. * @param particle is the particle we are computed the position for
  56801. */
  56802. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56803. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56804. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56805. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56806. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56807. };
  56808. /**
  56809. * Clones the current emitter and returns a copy of it
  56810. * @returns the new emitter
  56811. */
  56812. BoxParticleEmitter.prototype.clone = function () {
  56813. var newOne = new BoxParticleEmitter();
  56814. BABYLON.Tools.DeepCopy(this, newOne);
  56815. return newOne;
  56816. };
  56817. /**
  56818. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56819. * @param effect defines the update shader
  56820. */
  56821. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56822. effect.setVector3("direction1", this.direction1);
  56823. effect.setVector3("direction2", this.direction2);
  56824. effect.setVector3("minEmitBox", this.minEmitBox);
  56825. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56826. };
  56827. /**
  56828. * Returns a string to use to update the GPU particles update shader
  56829. * @returns a string containng the defines string
  56830. */
  56831. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56832. return "#define BOXEMITTER";
  56833. };
  56834. /**
  56835. * Returns the string "BoxEmitter"
  56836. * @returns a string containing the class name
  56837. */
  56838. BoxParticleEmitter.prototype.getClassName = function () {
  56839. return "BoxEmitter";
  56840. };
  56841. /**
  56842. * Serializes the particle system to a JSON object.
  56843. * @returns the JSON object
  56844. */
  56845. BoxParticleEmitter.prototype.serialize = function () {
  56846. var serializationObject = {};
  56847. serializationObject.type = this.getClassName();
  56848. serializationObject.direction1 = this.direction1.asArray();
  56849. serializationObject.direction2 = this.direction2.asArray();
  56850. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56851. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56852. return serializationObject;
  56853. };
  56854. /**
  56855. * Parse properties from a JSON object
  56856. * @param serializationObject defines the JSON object
  56857. */
  56858. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56859. this.direction1.copyFrom(serializationObject.direction1);
  56860. this.direction2.copyFrom(serializationObject.direction2);
  56861. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56862. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56863. };
  56864. return BoxParticleEmitter;
  56865. }());
  56866. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56867. })(BABYLON || (BABYLON = {}));
  56868. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56869. var BABYLON;
  56870. (function (BABYLON) {
  56871. /**
  56872. * Particle emitter emitting particles from the inside of a cone.
  56873. * It emits the particles alongside the cone volume from the base to the particle.
  56874. * The emission direction might be randomized.
  56875. */
  56876. var ConeParticleEmitter = /** @class */ (function () {
  56877. /**
  56878. * Creates a new instance ConeParticleEmitter
  56879. * @param radius the radius of the emission cone (1 by default)
  56880. * @param angles the cone base angle (PI by default)
  56881. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56882. */
  56883. function ConeParticleEmitter(radius,
  56884. /**
  56885. * The radius of the emission cone.
  56886. */
  56887. angle,
  56888. /**
  56889. * The cone base angle.
  56890. */
  56891. directionRandomizer) {
  56892. if (radius === void 0) { radius = 1; }
  56893. if (angle === void 0) { angle = Math.PI; }
  56894. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56895. this.angle = angle;
  56896. this.directionRandomizer = directionRandomizer;
  56897. this.radius = radius;
  56898. }
  56899. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56900. /**
  56901. * Gets the radius of the emission cone.
  56902. */
  56903. get: function () {
  56904. return this._radius;
  56905. },
  56906. /**
  56907. * Sets the radius of the emission cone.
  56908. */
  56909. set: function (value) {
  56910. this._radius = value;
  56911. if (this.angle !== 0) {
  56912. this._height = value / Math.tan(this.angle / 2);
  56913. }
  56914. else {
  56915. this._height = 1;
  56916. }
  56917. },
  56918. enumerable: true,
  56919. configurable: true
  56920. });
  56921. /**
  56922. * Called by the particle System when the direction is computed for the created particle.
  56923. * @param emitPower is the power of the particle (speed)
  56924. * @param worldMatrix is the world matrix of the particle system
  56925. * @param directionToUpdate is the direction vector to update with the result
  56926. * @param particle is the particle we are computed the direction for
  56927. */
  56928. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56929. if (this.angle === 0) {
  56930. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56931. }
  56932. else {
  56933. // measure the direction Vector from the emitter to the particle.
  56934. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56935. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56936. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56937. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56938. direction.x += randX;
  56939. direction.y += randY;
  56940. direction.z += randZ;
  56941. direction.normalize();
  56942. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56943. }
  56944. };
  56945. /**
  56946. * Called by the particle System when the position is computed for the created particle.
  56947. * @param worldMatrix is the world matrix of the particle system
  56948. * @param positionToUpdate is the position vector to update with the result
  56949. * @param particle is the particle we are computed the position for
  56950. */
  56951. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56952. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56953. var h = BABYLON.Scalar.RandomRange(0, 1);
  56954. // Better distribution in a cone at normal angles.
  56955. h = 1 - h * h;
  56956. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56957. radius = radius * h;
  56958. var randX = radius * Math.sin(s);
  56959. var randZ = radius * Math.cos(s);
  56960. var randY = h * this._height;
  56961. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56962. };
  56963. /**
  56964. * Clones the current emitter and returns a copy of it
  56965. * @returns the new emitter
  56966. */
  56967. ConeParticleEmitter.prototype.clone = function () {
  56968. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56969. BABYLON.Tools.DeepCopy(this, newOne);
  56970. return newOne;
  56971. };
  56972. /**
  56973. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56974. * @param effect defines the update shader
  56975. */
  56976. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56977. effect.setFloat("radius", this.radius);
  56978. effect.setFloat("angle", this.angle);
  56979. effect.setFloat("height", this._height);
  56980. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56981. };
  56982. /**
  56983. * Returns a string to use to update the GPU particles update shader
  56984. * @returns a string containng the defines string
  56985. */
  56986. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56987. return "#define CONEEMITTER";
  56988. };
  56989. /**
  56990. * Returns the string "BoxEmitter"
  56991. * @returns a string containing the class name
  56992. */
  56993. ConeParticleEmitter.prototype.getClassName = function () {
  56994. return "ConeEmitter";
  56995. };
  56996. /**
  56997. * Serializes the particle system to a JSON object.
  56998. * @returns the JSON object
  56999. */
  57000. ConeParticleEmitter.prototype.serialize = function () {
  57001. var serializationObject = {};
  57002. serializationObject.type = this.getClassName();
  57003. serializationObject.radius = this.radius;
  57004. serializationObject.angle = this.angle;
  57005. serializationObject.directionRandomizer = this.directionRandomizer;
  57006. return serializationObject;
  57007. };
  57008. /**
  57009. * Parse properties from a JSON object
  57010. * @param serializationObject defines the JSON object
  57011. */
  57012. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57013. this.radius = serializationObject.radius;
  57014. this.angle = serializationObject.angle;
  57015. this.directionRandomizer = serializationObject.directionRandomizer;
  57016. };
  57017. return ConeParticleEmitter;
  57018. }());
  57019. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57020. })(BABYLON || (BABYLON = {}));
  57021. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57022. var BABYLON;
  57023. (function (BABYLON) {
  57024. /**
  57025. * Particle emitter emitting particles from the inside of a sphere.
  57026. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57027. */
  57028. var SphereParticleEmitter = /** @class */ (function () {
  57029. /**
  57030. * Creates a new instance SphereParticleEmitter
  57031. * @param radius the radius of the emission sphere (1 by default)
  57032. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57033. */
  57034. function SphereParticleEmitter(
  57035. /**
  57036. * The radius of the emission sphere.
  57037. */
  57038. radius,
  57039. /**
  57040. * How much to randomize the particle direction [0-1].
  57041. */
  57042. directionRandomizer) {
  57043. if (radius === void 0) { radius = 1; }
  57044. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57045. this.radius = radius;
  57046. this.directionRandomizer = directionRandomizer;
  57047. }
  57048. /**
  57049. * Called by the particle System when the direction is computed for the created particle.
  57050. * @param emitPower is the power of the particle (speed)
  57051. * @param worldMatrix is the world matrix of the particle system
  57052. * @param directionToUpdate is the direction vector to update with the result
  57053. * @param particle is the particle we are computed the direction for
  57054. */
  57055. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57056. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57057. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57058. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57059. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57060. direction.x += randX;
  57061. direction.y += randY;
  57062. direction.z += randZ;
  57063. direction.normalize();
  57064. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57065. };
  57066. /**
  57067. * Called by the particle System when the position is computed for the created particle.
  57068. * @param worldMatrix is the world matrix of the particle system
  57069. * @param positionToUpdate is the position vector to update with the result
  57070. * @param particle is the particle we are computed the position for
  57071. */
  57072. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57073. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57074. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57075. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57076. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57077. var randY = randRadius * Math.cos(theta);
  57078. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57079. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57080. };
  57081. /**
  57082. * Clones the current emitter and returns a copy of it
  57083. * @returns the new emitter
  57084. */
  57085. SphereParticleEmitter.prototype.clone = function () {
  57086. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57087. BABYLON.Tools.DeepCopy(this, newOne);
  57088. return newOne;
  57089. };
  57090. /**
  57091. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57092. * @param effect defines the update shader
  57093. */
  57094. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57095. effect.setFloat("radius", this.radius);
  57096. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57097. };
  57098. /**
  57099. * Returns a string to use to update the GPU particles update shader
  57100. * @returns a string containng the defines string
  57101. */
  57102. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57103. return "#define SPHEREEMITTER";
  57104. };
  57105. /**
  57106. * Returns the string "SphereParticleEmitter"
  57107. * @returns a string containing the class name
  57108. */
  57109. SphereParticleEmitter.prototype.getClassName = function () {
  57110. return "SphereParticleEmitter";
  57111. };
  57112. /**
  57113. * Serializes the particle system to a JSON object.
  57114. * @returns the JSON object
  57115. */
  57116. SphereParticleEmitter.prototype.serialize = function () {
  57117. var serializationObject = {};
  57118. serializationObject.type = this.getClassName();
  57119. serializationObject.radius = this.radius;
  57120. serializationObject.directionRandomizer = this.directionRandomizer;
  57121. return serializationObject;
  57122. };
  57123. /**
  57124. * Parse properties from a JSON object
  57125. * @param serializationObject defines the JSON object
  57126. */
  57127. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57128. this.radius = serializationObject.radius;
  57129. this.directionRandomizer = serializationObject.directionRandomizer;
  57130. };
  57131. return SphereParticleEmitter;
  57132. }());
  57133. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57134. /**
  57135. * Particle emitter emitting particles from the inside of a sphere.
  57136. * It emits the particles randomly between two vectors.
  57137. */
  57138. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57139. __extends(SphereDirectedParticleEmitter, _super);
  57140. /**
  57141. * Creates a new instance SphereDirectedParticleEmitter
  57142. * @param radius the radius of the emission sphere (1 by default)
  57143. * @param direction1 the min limit of the emission direction (up vector by default)
  57144. * @param direction2 the max limit of the emission direction (up vector by default)
  57145. */
  57146. function SphereDirectedParticleEmitter(radius,
  57147. /**
  57148. * The min limit of the emission direction.
  57149. */
  57150. direction1,
  57151. /**
  57152. * The max limit of the emission direction.
  57153. */
  57154. direction2) {
  57155. if (radius === void 0) { radius = 1; }
  57156. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57157. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57158. var _this = _super.call(this, radius) || this;
  57159. _this.direction1 = direction1;
  57160. _this.direction2 = direction2;
  57161. return _this;
  57162. }
  57163. /**
  57164. * Called by the particle System when the direction is computed for the created particle.
  57165. * @param emitPower is the power of the particle (speed)
  57166. * @param worldMatrix is the world matrix of the particle system
  57167. * @param directionToUpdate is the direction vector to update with the result
  57168. * @param particle is the particle we are computed the direction for
  57169. */
  57170. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57171. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57172. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57173. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57174. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57175. };
  57176. /**
  57177. * Clones the current emitter and returns a copy of it
  57178. * @returns the new emitter
  57179. */
  57180. SphereDirectedParticleEmitter.prototype.clone = function () {
  57181. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57182. BABYLON.Tools.DeepCopy(this, newOne);
  57183. return newOne;
  57184. };
  57185. /**
  57186. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57187. * @param effect defines the update shader
  57188. */
  57189. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57190. effect.setFloat("radius", this.radius);
  57191. effect.setVector3("direction1", this.direction1);
  57192. effect.setVector3("direction2", this.direction2);
  57193. };
  57194. /**
  57195. * Returns a string to use to update the GPU particles update shader
  57196. * @returns a string containng the defines string
  57197. */
  57198. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57199. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57200. };
  57201. /**
  57202. * Returns the string "SphereDirectedParticleEmitter"
  57203. * @returns a string containing the class name
  57204. */
  57205. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57206. return "SphereDirectedParticleEmitter";
  57207. };
  57208. /**
  57209. * Serializes the particle system to a JSON object.
  57210. * @returns the JSON object
  57211. */
  57212. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57213. var serializationObject = _super.prototype.serialize.call(this);
  57214. serializationObject.direction1 = this.direction1.asArray();
  57215. serializationObject.direction2 = this.direction2.asArray();
  57216. return serializationObject;
  57217. };
  57218. /**
  57219. * Parse properties from a JSON object
  57220. * @param serializationObject defines the JSON object
  57221. */
  57222. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57223. _super.prototype.parse.call(this, serializationObject);
  57224. this.direction1.copyFrom(serializationObject.direction1);
  57225. this.direction2.copyFrom(serializationObject.direction2);
  57226. };
  57227. return SphereDirectedParticleEmitter;
  57228. }(SphereParticleEmitter));
  57229. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57230. })(BABYLON || (BABYLON = {}));
  57231. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57232. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57233. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57234. s = arguments[i];
  57235. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57236. t[p] = s[p];
  57237. }
  57238. return t;
  57239. };
  57240. var BABYLON;
  57241. (function (BABYLON) {
  57242. /**
  57243. * This represents a GPU particle system in Babylon
  57244. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57245. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57246. */
  57247. var GPUParticleSystem = /** @class */ (function () {
  57248. /**
  57249. * Instantiates a GPU particle system.
  57250. * 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.
  57251. * @param name The name of the particle system
  57252. * @param capacity The max number of particles alive at the same time
  57253. * @param scene The scene the particle system belongs to
  57254. */
  57255. function GPUParticleSystem(name, options, scene) {
  57256. /**
  57257. * The emitter represents the Mesh or position we are attaching the particle system to.
  57258. */
  57259. this.emitter = null;
  57260. /**
  57261. * The rendering group used by the Particle system to chose when to render.
  57262. */
  57263. this.renderingGroupId = 0;
  57264. /**
  57265. * The layer mask we are rendering the particles through.
  57266. */
  57267. this.layerMask = 0x0FFFFFFF;
  57268. this._targetIndex = 0;
  57269. this._currentRenderId = -1;
  57270. this._started = false;
  57271. this._stopped = false;
  57272. this._timeDelta = 0;
  57273. this._attributesStrideSize = 14;
  57274. this._actualFrame = 0;
  57275. /**
  57276. * List of animations used by the particle system.
  57277. */
  57278. this.animations = [];
  57279. /**
  57280. * An event triggered when the system is disposed.
  57281. */
  57282. this.onDisposeObservable = new BABYLON.Observable();
  57283. /**
  57284. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57285. */
  57286. this.updateSpeed = 0.01;
  57287. /**
  57288. * The amount of time the particle system is running (depends of the overall update speed).
  57289. */
  57290. this.targetStopDuration = 0;
  57291. /**
  57292. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57293. */
  57294. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57295. /**
  57296. * Minimum life time of emitting particles.
  57297. */
  57298. this.minLifeTime = 1;
  57299. /**
  57300. * Maximum life time of emitting particles.
  57301. */
  57302. this.maxLifeTime = 1;
  57303. /**
  57304. * Minimum Size of emitting particles.
  57305. */
  57306. this.minSize = 1;
  57307. /**
  57308. * Maximum Size of emitting particles.
  57309. */
  57310. this.maxSize = 1;
  57311. /**
  57312. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57313. */
  57314. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57315. /**
  57316. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57317. */
  57318. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57319. /**
  57320. * Color the particle will have at the end of its lifetime.
  57321. */
  57322. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57323. /**
  57324. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57325. */
  57326. this.emitRate = 100;
  57327. /**
  57328. * You can use gravity if you want to give an orientation to your particles.
  57329. */
  57330. this.gravity = BABYLON.Vector3.Zero();
  57331. /**
  57332. * Minimum power of emitting particles.
  57333. */
  57334. this.minEmitPower = 1;
  57335. /**
  57336. * Maximum power of emitting particles.
  57337. */
  57338. this.maxEmitPower = 1;
  57339. /**
  57340. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57341. * to override the particles.
  57342. */
  57343. this.forceDepthWrite = false;
  57344. this.id = name;
  57345. this.name = name;
  57346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57347. this._engine = this._scene.getEngine();
  57348. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57349. this._capacity = fullOptions.capacity;
  57350. this._activeCount = fullOptions.capacity;
  57351. this._currentActiveCount = 0;
  57352. this._scene.particleSystems.push(this);
  57353. this._updateEffectOptions = {
  57354. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57355. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57356. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57357. uniformBuffersNames: [],
  57358. samplers: ["randomSampler"],
  57359. defines: "",
  57360. fallbacks: null,
  57361. onCompiled: null,
  57362. onError: null,
  57363. indexParameters: null,
  57364. maxSimultaneousLights: 0,
  57365. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57366. };
  57367. // Random data
  57368. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57369. var d = [];
  57370. for (var i = 0; i < maxTextureSize; ++i) {
  57371. d.push(Math.random());
  57372. d.push(Math.random());
  57373. d.push(Math.random());
  57374. d.push(Math.random());
  57375. }
  57376. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57377. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57378. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57379. this._randomTextureSize = maxTextureSize;
  57380. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57381. }
  57382. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57383. /**
  57384. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57385. */
  57386. get: function () {
  57387. if (!BABYLON.Engine.LastCreatedEngine) {
  57388. return false;
  57389. }
  57390. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57391. },
  57392. enumerable: true,
  57393. configurable: true
  57394. });
  57395. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57396. /**
  57397. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57398. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57399. */
  57400. get: function () {
  57401. if (this.particleEmitterType.direction1) {
  57402. return this.particleEmitterType.direction1;
  57403. }
  57404. return BABYLON.Vector3.Zero();
  57405. },
  57406. set: function (value) {
  57407. if (this.particleEmitterType.direction1) {
  57408. this.particleEmitterType.direction1 = value;
  57409. }
  57410. },
  57411. enumerable: true,
  57412. configurable: true
  57413. });
  57414. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57415. /**
  57416. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57417. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57418. */
  57419. get: function () {
  57420. if (this.particleEmitterType.direction2) {
  57421. return this.particleEmitterType.direction2;
  57422. }
  57423. return BABYLON.Vector3.Zero();
  57424. },
  57425. set: function (value) {
  57426. if (this.particleEmitterType.direction2) {
  57427. this.particleEmitterType.direction2 = value;
  57428. }
  57429. },
  57430. enumerable: true,
  57431. configurable: true
  57432. });
  57433. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57434. /**
  57435. * 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.
  57436. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57437. */
  57438. get: function () {
  57439. if (this.particleEmitterType.minEmitBox) {
  57440. return this.particleEmitterType.minEmitBox;
  57441. }
  57442. return BABYLON.Vector3.Zero();
  57443. },
  57444. set: function (value) {
  57445. if (this.particleEmitterType.minEmitBox) {
  57446. this.particleEmitterType.minEmitBox = value;
  57447. }
  57448. },
  57449. enumerable: true,
  57450. configurable: true
  57451. });
  57452. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57453. /**
  57454. * 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.
  57455. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57456. */
  57457. get: function () {
  57458. if (this.particleEmitterType.maxEmitBox) {
  57459. return this.particleEmitterType.maxEmitBox;
  57460. }
  57461. return BABYLON.Vector3.Zero();
  57462. },
  57463. set: function (value) {
  57464. if (this.particleEmitterType.maxEmitBox) {
  57465. this.particleEmitterType.maxEmitBox = value;
  57466. }
  57467. },
  57468. enumerable: true,
  57469. configurable: true
  57470. });
  57471. /**
  57472. * Gets the maximum number of particles active at the same time.
  57473. * @returns The max number of active particles.
  57474. */
  57475. GPUParticleSystem.prototype.getCapacity = function () {
  57476. return this._capacity;
  57477. };
  57478. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57479. /**
  57480. * Gets or set the number of active particles
  57481. */
  57482. get: function () {
  57483. return this._activeCount;
  57484. },
  57485. set: function (value) {
  57486. this._activeCount = Math.min(value, this._capacity);
  57487. },
  57488. enumerable: true,
  57489. configurable: true
  57490. });
  57491. /**
  57492. * Is this system ready to be used/rendered
  57493. * @return true if the system is ready
  57494. */
  57495. GPUParticleSystem.prototype.isReady = function () {
  57496. if (!this._updateEffect) {
  57497. this._recreateUpdateEffect();
  57498. this._recreateRenderEffect();
  57499. return false;
  57500. }
  57501. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57502. return false;
  57503. }
  57504. return true;
  57505. };
  57506. /**
  57507. * Gets Wether the system has been started.
  57508. * @returns True if it has been started, otherwise false.
  57509. */
  57510. GPUParticleSystem.prototype.isStarted = function () {
  57511. return this._started;
  57512. };
  57513. /**
  57514. * Starts the particle system and begins to emit.
  57515. */
  57516. GPUParticleSystem.prototype.start = function () {
  57517. this._started = true;
  57518. this._stopped = false;
  57519. };
  57520. /**
  57521. * Stops the particle system.
  57522. */
  57523. GPUParticleSystem.prototype.stop = function () {
  57524. this._stopped = true;
  57525. };
  57526. /**
  57527. * Remove all active particles
  57528. */
  57529. GPUParticleSystem.prototype.reset = function () {
  57530. this._releaseBuffers();
  57531. this._releaseVAOs();
  57532. this._currentActiveCount = 0;
  57533. this._targetIndex = 0;
  57534. };
  57535. /**
  57536. * Returns the string "GPUParticleSystem"
  57537. * @returns a string containing the class name
  57538. */
  57539. GPUParticleSystem.prototype.getClassName = function () {
  57540. return "GPUParticleSystem";
  57541. };
  57542. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57543. var updateVertexBuffers = {};
  57544. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57545. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57546. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57547. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57548. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57549. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57550. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57551. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57552. this._engine.bindArrayBuffer(null);
  57553. return vao;
  57554. };
  57555. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57556. var renderVertexBuffers = {};
  57557. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57558. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57559. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57560. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57561. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57562. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57563. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57564. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57565. this._engine.bindArrayBuffer(null);
  57566. return vao;
  57567. };
  57568. GPUParticleSystem.prototype._initialize = function (force) {
  57569. if (force === void 0) { force = false; }
  57570. if (this._buffer0 && !force) {
  57571. return;
  57572. }
  57573. var engine = this._scene.getEngine();
  57574. var data = new Array();
  57575. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57576. // position
  57577. data.push(0.0);
  57578. data.push(0.0);
  57579. data.push(0.0);
  57580. // Age and life
  57581. data.push(0.0); // create the particle as a dead one to create a new one at start
  57582. data.push(0.0);
  57583. // Seed
  57584. data.push(Math.random());
  57585. // Size
  57586. data.push(0.0);
  57587. // color
  57588. data.push(0.0);
  57589. data.push(0.0);
  57590. data.push(0.0);
  57591. data.push(0.0);
  57592. // direction
  57593. data.push(0.0);
  57594. data.push(0.0);
  57595. data.push(0.0);
  57596. }
  57597. // Sprite data
  57598. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57599. -0.5, 0.5, 0, 1,
  57600. -0.5, -0.5, 0, 0,
  57601. 0.5, -0.5, 1, 0]);
  57602. // Buffers
  57603. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57604. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57605. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57606. // Update VAO
  57607. this._updateVAO = [];
  57608. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57609. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57610. // Render VAO
  57611. this._renderVAO = [];
  57612. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57613. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57614. // Links
  57615. this._sourceBuffer = this._buffer0;
  57616. this._targetBuffer = this._buffer1;
  57617. };
  57618. /** @hidden */
  57619. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57620. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57621. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57622. return;
  57623. }
  57624. this._updateEffectOptions.defines = defines;
  57625. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57626. };
  57627. /** @hidden */
  57628. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57629. var defines = "";
  57630. if (this._scene.clipPlane) {
  57631. defines = "\n#define CLIPPLANE";
  57632. }
  57633. if (this._renderEffect && this._renderEffect.defines === defines) {
  57634. return;
  57635. }
  57636. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57637. };
  57638. /**
  57639. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57640. */
  57641. GPUParticleSystem.prototype.animate = function () {
  57642. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57643. this._actualFrame += this._timeDelta;
  57644. if (!this._stopped) {
  57645. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57646. this.stop();
  57647. }
  57648. }
  57649. };
  57650. /**
  57651. * Renders the particle system in its current state.
  57652. * @returns the current number of particles
  57653. */
  57654. GPUParticleSystem.prototype.render = function () {
  57655. if (!this._started) {
  57656. return 0;
  57657. }
  57658. this._recreateUpdateEffect();
  57659. this._recreateRenderEffect();
  57660. if (!this.isReady()) {
  57661. return 0;
  57662. }
  57663. if (this._currentRenderId === this._scene.getRenderId()) {
  57664. return 0;
  57665. }
  57666. this._currentRenderId = this._scene.getRenderId();
  57667. // Get everything ready to render
  57668. this._initialize();
  57669. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57670. // Enable update effect
  57671. this._engine.enableEffect(this._updateEffect);
  57672. this._engine.setState(false);
  57673. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57674. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57675. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57676. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57677. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57678. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57679. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57680. this._updateEffect.setDirectColor4("color1", this.color1);
  57681. this._updateEffect.setDirectColor4("color2", this.color2);
  57682. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57683. this._updateEffect.setVector3("gravity", this.gravity);
  57684. if (this.particleEmitterType) {
  57685. this.particleEmitterType.applyToShader(this._updateEffect);
  57686. }
  57687. var emitterWM;
  57688. if (this.emitter.position) {
  57689. var emitterMesh = this.emitter;
  57690. emitterWM = emitterMesh.getWorldMatrix();
  57691. }
  57692. else {
  57693. var emitterPosition = this.emitter;
  57694. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57695. }
  57696. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57697. // Bind source VAO
  57698. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57699. // Update
  57700. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57701. this._engine.setRasterizerState(false);
  57702. this._engine.beginTransformFeedback();
  57703. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57704. this._engine.endTransformFeedback();
  57705. this._engine.setRasterizerState(true);
  57706. this._engine.bindTransformFeedbackBuffer(null);
  57707. // Enable render effect
  57708. this._engine.enableEffect(this._renderEffect);
  57709. var viewMatrix = this._scene.getViewMatrix();
  57710. this._renderEffect.setMatrix("view", viewMatrix);
  57711. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57712. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57713. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57714. if (this._scene.clipPlane) {
  57715. var clipPlane = this._scene.clipPlane;
  57716. var invView = viewMatrix.clone();
  57717. invView.invert();
  57718. this._renderEffect.setMatrix("invView", invView);
  57719. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57720. }
  57721. // Draw order
  57722. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57723. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57724. }
  57725. else {
  57726. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57727. }
  57728. if (this.forceDepthWrite) {
  57729. this._engine.setDepthWrite(true);
  57730. }
  57731. // Bind source VAO
  57732. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57733. // Render
  57734. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57735. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57736. // Switch VAOs
  57737. this._targetIndex++;
  57738. if (this._targetIndex === 2) {
  57739. this._targetIndex = 0;
  57740. }
  57741. // Switch buffers
  57742. var tmpBuffer = this._sourceBuffer;
  57743. this._sourceBuffer = this._targetBuffer;
  57744. this._targetBuffer = tmpBuffer;
  57745. return this._currentActiveCount;
  57746. };
  57747. /**
  57748. * Rebuilds the particle system
  57749. */
  57750. GPUParticleSystem.prototype.rebuild = function () {
  57751. this._initialize(true);
  57752. };
  57753. GPUParticleSystem.prototype._releaseBuffers = function () {
  57754. if (this._buffer0) {
  57755. this._buffer0.dispose();
  57756. this._buffer0 = null;
  57757. }
  57758. if (this._buffer1) {
  57759. this._buffer1.dispose();
  57760. this._buffer1 = null;
  57761. }
  57762. if (this._spriteBuffer) {
  57763. this._spriteBuffer.dispose();
  57764. this._spriteBuffer = null;
  57765. }
  57766. };
  57767. GPUParticleSystem.prototype._releaseVAOs = function () {
  57768. if (!this._updateVAO) {
  57769. return;
  57770. }
  57771. for (var index = 0; index < this._updateVAO.length; index++) {
  57772. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57773. }
  57774. this._updateVAO = [];
  57775. for (var index = 0; index < this._renderVAO.length; index++) {
  57776. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57777. }
  57778. this._renderVAO = [];
  57779. };
  57780. /**
  57781. * Disposes the particle system and free the associated resources
  57782. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57783. */
  57784. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57785. if (disposeTexture === void 0) { disposeTexture = true; }
  57786. var index = this._scene.particleSystems.indexOf(this);
  57787. if (index > -1) {
  57788. this._scene.particleSystems.splice(index, 1);
  57789. }
  57790. this._releaseBuffers();
  57791. this._releaseVAOs();
  57792. if (this._randomTexture) {
  57793. this._randomTexture.dispose();
  57794. this._randomTexture = null;
  57795. }
  57796. if (disposeTexture && this.particleTexture) {
  57797. this.particleTexture.dispose();
  57798. this.particleTexture = null;
  57799. }
  57800. // Callback
  57801. this.onDisposeObservable.notifyObservers(this);
  57802. this.onDisposeObservable.clear();
  57803. };
  57804. /**
  57805. * Clones the particle system.
  57806. * @param name The name of the cloned object
  57807. * @param newEmitter The new emitter to use
  57808. * @returns the cloned particle system
  57809. */
  57810. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57811. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57812. BABYLON.Tools.DeepCopy(this, result);
  57813. if (newEmitter === undefined) {
  57814. newEmitter = this.emitter;
  57815. }
  57816. result.emitter = newEmitter;
  57817. if (this.particleTexture) {
  57818. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57819. }
  57820. return result;
  57821. };
  57822. /**
  57823. * Serializes the particle system to a JSON object.
  57824. * @returns the JSON object
  57825. */
  57826. GPUParticleSystem.prototype.serialize = function () {
  57827. var serializationObject = {};
  57828. serializationObject.name = this.name;
  57829. serializationObject.id = this.id;
  57830. // Emitter
  57831. if (this.emitter.position) {
  57832. var emitterMesh = this.emitter;
  57833. serializationObject.emitterId = emitterMesh.id;
  57834. }
  57835. else {
  57836. var emitterPosition = this.emitter;
  57837. serializationObject.emitter = emitterPosition.asArray();
  57838. }
  57839. serializationObject.capacity = this.getCapacity();
  57840. if (this.particleTexture) {
  57841. serializationObject.textureName = this.particleTexture.name;
  57842. }
  57843. // Animations
  57844. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57845. // Particle system
  57846. serializationObject.activeParticleCount = this.activeParticleCount;
  57847. serializationObject.randomTextureSize = this._randomTextureSize;
  57848. serializationObject.minSize = this.minSize;
  57849. serializationObject.maxSize = this.maxSize;
  57850. serializationObject.minEmitPower = this.minEmitPower;
  57851. serializationObject.maxEmitPower = this.maxEmitPower;
  57852. serializationObject.minLifeTime = this.minLifeTime;
  57853. serializationObject.maxLifeTime = this.maxLifeTime;
  57854. serializationObject.emitRate = this.emitRate;
  57855. serializationObject.gravity = this.gravity.asArray();
  57856. serializationObject.color1 = this.color1.asArray();
  57857. serializationObject.color2 = this.color2.asArray();
  57858. serializationObject.colorDead = this.colorDead.asArray();
  57859. serializationObject.updateSpeed = this.updateSpeed;
  57860. serializationObject.targetStopDuration = this.targetStopDuration;
  57861. serializationObject.blendMode = this.blendMode;
  57862. // Emitter
  57863. if (this.particleEmitterType) {
  57864. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57865. }
  57866. return serializationObject;
  57867. };
  57868. /**
  57869. * Parses a JSON object to create a GPU particle system.
  57870. * @param parsedParticleSystem The JSON object to parse
  57871. * @param scene The scene to create the particle system in
  57872. * @param rootUrl The root url to use to load external dependencies like texture
  57873. * @returns the parsed GPU particle system
  57874. */
  57875. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57876. var name = parsedParticleSystem.name;
  57877. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57878. if (parsedParticleSystem.id) {
  57879. particleSystem.id = parsedParticleSystem.id;
  57880. }
  57881. // Texture
  57882. if (parsedParticleSystem.textureName) {
  57883. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57884. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57885. }
  57886. // Emitter
  57887. if (parsedParticleSystem.emitterId) {
  57888. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57889. }
  57890. else {
  57891. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57892. }
  57893. // Animations
  57894. if (parsedParticleSystem.animations) {
  57895. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57896. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57897. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57898. }
  57899. }
  57900. // Particle system
  57901. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57902. particleSystem.minSize = parsedParticleSystem.minSize;
  57903. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57904. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57905. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57906. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57907. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57908. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57909. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57910. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57911. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57912. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57913. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57914. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57915. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57916. // Emitter
  57917. if (parsedParticleSystem.particleEmitterType) {
  57918. var emitterType = void 0;
  57919. switch (parsedParticleSystem.particleEmitterType.type) {
  57920. case "SphereEmitter":
  57921. emitterType = new BABYLON.SphereParticleEmitter();
  57922. break;
  57923. case "SphereDirectedParticleEmitter":
  57924. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57925. break;
  57926. case "ConeEmitter":
  57927. emitterType = new BABYLON.ConeParticleEmitter();
  57928. break;
  57929. case "BoxEmitter":
  57930. default:
  57931. emitterType = new BABYLON.BoxParticleEmitter();
  57932. break;
  57933. }
  57934. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57935. particleSystem.particleEmitterType = emitterType;
  57936. }
  57937. return particleSystem;
  57938. };
  57939. return GPUParticleSystem;
  57940. }());
  57941. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57942. })(BABYLON || (BABYLON = {}));
  57943. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57944. var BABYLON;
  57945. (function (BABYLON) {
  57946. /**
  57947. * Represents one particle of a solid particle system.
  57948. */
  57949. var SolidParticle = /** @class */ (function () {
  57950. /**
  57951. * Creates a Solid Particle object.
  57952. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57953. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57954. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57955. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57956. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57957. * @param shapeId (integer) is the model shape identifier in the SPS.
  57958. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57959. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57960. */
  57961. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57962. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57963. /**
  57964. * particle global index
  57965. */
  57966. this.idx = 0;
  57967. /**
  57968. * The color of the particle
  57969. */
  57970. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57971. /**
  57972. * The world space position of the particle.
  57973. */
  57974. this.position = BABYLON.Vector3.Zero();
  57975. /**
  57976. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57977. */
  57978. this.rotation = BABYLON.Vector3.Zero();
  57979. /**
  57980. * The scaling of the particle.
  57981. */
  57982. this.scaling = BABYLON.Vector3.One();
  57983. /**
  57984. * The uvs of the particle.
  57985. */
  57986. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57987. /**
  57988. * The current speed of the particle.
  57989. */
  57990. this.velocity = BABYLON.Vector3.Zero();
  57991. /**
  57992. * The pivot point in the particle local space.
  57993. */
  57994. this.pivot = BABYLON.Vector3.Zero();
  57995. /**
  57996. * Must the particle be translated from its pivot point in its local space ?
  57997. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57998. * Default : false
  57999. */
  58000. this.translateFromPivot = false;
  58001. /**
  58002. * Is the particle active or not ?
  58003. */
  58004. this.alive = true;
  58005. /**
  58006. * Is the particle visible or not ?
  58007. */
  58008. this.isVisible = true;
  58009. /**
  58010. * Index of this particle in the global "positions" array (Internal use)
  58011. */
  58012. this._pos = 0;
  58013. /**
  58014. * Index of this particle in the global "indices" array (Internal use)
  58015. */
  58016. this._ind = 0;
  58017. /**
  58018. * ModelShape id of this particle
  58019. */
  58020. this.shapeId = 0;
  58021. /**
  58022. * Index of the particle in its shape id (Internal use)
  58023. */
  58024. this.idxInShape = 0;
  58025. /**
  58026. * Still set as invisible in order to skip useless computations (Internal use)
  58027. */
  58028. this._stillInvisible = false;
  58029. /**
  58030. * Last computed particle rotation matrix
  58031. */
  58032. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58033. /**
  58034. * Parent particle Id, if any.
  58035. * Default null.
  58036. */
  58037. this.parentId = null;
  58038. /**
  58039. * Internal global position in the SPS.
  58040. */
  58041. this._globalPosition = BABYLON.Vector3.Zero();
  58042. this.idx = particleIndex;
  58043. this._pos = positionIndex;
  58044. this._ind = indiceIndex;
  58045. this._model = model;
  58046. this.shapeId = shapeId;
  58047. this.idxInShape = idxInShape;
  58048. this._sps = sps;
  58049. if (modelBoundingInfo) {
  58050. this._modelBoundingInfo = modelBoundingInfo;
  58051. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58052. }
  58053. }
  58054. Object.defineProperty(SolidParticle.prototype, "scale", {
  58055. /**
  58056. * Legacy support, changed scale to scaling
  58057. */
  58058. get: function () {
  58059. return this.scaling;
  58060. },
  58061. /**
  58062. * Legacy support, changed scale to scaling
  58063. */
  58064. set: function (scale) {
  58065. this.scaling = scale;
  58066. },
  58067. enumerable: true,
  58068. configurable: true
  58069. });
  58070. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58071. /**
  58072. * Legacy support, changed quaternion to rotationQuaternion
  58073. */
  58074. get: function () {
  58075. return this.rotationQuaternion;
  58076. },
  58077. /**
  58078. * Legacy support, changed quaternion to rotationQuaternion
  58079. */
  58080. set: function (q) {
  58081. this.rotationQuaternion = q;
  58082. },
  58083. enumerable: true,
  58084. configurable: true
  58085. });
  58086. /**
  58087. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58088. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58089. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58090. * @returns true if it intersects
  58091. */
  58092. SolidParticle.prototype.intersectsMesh = function (target) {
  58093. if (!this._boundingInfo || !target._boundingInfo) {
  58094. return false;
  58095. }
  58096. if (this._sps._bSphereOnly) {
  58097. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58098. }
  58099. return this._boundingInfo.intersects(target._boundingInfo, false);
  58100. };
  58101. return SolidParticle;
  58102. }());
  58103. BABYLON.SolidParticle = SolidParticle;
  58104. /**
  58105. * Represents the shape of the model used by one particle of a solid particle system.
  58106. * SPS internal tool, don't use it manually.
  58107. */
  58108. var ModelShape = /** @class */ (function () {
  58109. /**
  58110. * 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.
  58111. * SPS internal tool, don't use it manually.
  58112. * @hidden
  58113. */
  58114. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58115. /**
  58116. * length of the shape in the model indices array (internal use)
  58117. */
  58118. this._indicesLength = 0;
  58119. this.shapeID = id;
  58120. this._shape = shape;
  58121. this._indicesLength = indicesLength;
  58122. this._shapeUV = shapeUV;
  58123. this._positionFunction = posFunction;
  58124. this._vertexFunction = vtxFunction;
  58125. }
  58126. return ModelShape;
  58127. }());
  58128. BABYLON.ModelShape = ModelShape;
  58129. /**
  58130. * Represents a Depth Sorted Particle in the solid particle system.
  58131. */
  58132. var DepthSortedParticle = /** @class */ (function () {
  58133. function DepthSortedParticle() {
  58134. /**
  58135. * Index of the particle in the "indices" array
  58136. */
  58137. this.ind = 0;
  58138. /**
  58139. * Length of the particle shape in the "indices" array
  58140. */
  58141. this.indicesLength = 0;
  58142. /**
  58143. * Squared distance from the particle to the camera
  58144. */
  58145. this.sqDistance = 0.0;
  58146. }
  58147. return DepthSortedParticle;
  58148. }());
  58149. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58150. })(BABYLON || (BABYLON = {}));
  58151. //# sourceMappingURL=babylon.solidParticle.js.map
  58152. var BABYLON;
  58153. (function (BABYLON) {
  58154. /**
  58155. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58156. *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.
  58157. * The SPS is also a particle system. It provides some methods to manage the particles.
  58158. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58159. *
  58160. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58161. */
  58162. var SolidParticleSystem = /** @class */ (function () {
  58163. /**
  58164. * Creates a SPS (Solid Particle System) object.
  58165. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58166. * @param scene (Scene) is the scene in which the SPS is added.
  58167. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58168. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58169. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58170. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58171. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58172. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58173. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58174. */
  58175. function SolidParticleSystem(name, scene, options) {
  58176. /**
  58177. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58178. * Example : var p = SPS.particles[i];
  58179. */
  58180. this.particles = new Array();
  58181. /**
  58182. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58183. */
  58184. this.nbParticles = 0;
  58185. /**
  58186. * If the particles must ever face the camera (default false). Useful for planar particles.
  58187. */
  58188. this.billboard = false;
  58189. /**
  58190. * Recompute normals when adding a shape
  58191. */
  58192. this.recomputeNormals = true;
  58193. /**
  58194. * This a counter ofr your own usage. It's not set by any SPS functions.
  58195. */
  58196. this.counter = 0;
  58197. /**
  58198. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58199. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58200. */
  58201. this.vars = {};
  58202. /**
  58203. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58204. */
  58205. this._bSphereOnly = false;
  58206. /**
  58207. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58208. */
  58209. this._bSphereRadiusFactor = 1.0;
  58210. this._positions = new Array();
  58211. this._indices = new Array();
  58212. this._normals = new Array();
  58213. this._colors = new Array();
  58214. this._uvs = new Array();
  58215. this._index = 0; // indices index
  58216. this._updatable = true;
  58217. this._pickable = false;
  58218. this._isVisibilityBoxLocked = false;
  58219. this._alwaysVisible = false;
  58220. this._depthSort = false;
  58221. this._shapeCounter = 0;
  58222. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58223. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58224. this._computeParticleColor = true;
  58225. this._computeParticleTexture = true;
  58226. this._computeParticleRotation = true;
  58227. this._computeParticleVertex = false;
  58228. this._computeBoundingBox = false;
  58229. this._depthSortParticles = true;
  58230. this._cam_axisZ = BABYLON.Vector3.Zero();
  58231. this._cam_axisY = BABYLON.Vector3.Zero();
  58232. this._cam_axisX = BABYLON.Vector3.Zero();
  58233. this._axisZ = BABYLON.Axis.Z;
  58234. this._camDir = BABYLON.Vector3.Zero();
  58235. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58236. this._rotMatrix = new BABYLON.Matrix();
  58237. this._invertMatrix = new BABYLON.Matrix();
  58238. this._rotated = BABYLON.Vector3.Zero();
  58239. this._quaternion = new BABYLON.Quaternion();
  58240. this._vertex = BABYLON.Vector3.Zero();
  58241. this._normal = BABYLON.Vector3.Zero();
  58242. this._yaw = 0.0;
  58243. this._pitch = 0.0;
  58244. this._roll = 0.0;
  58245. this._halfroll = 0.0;
  58246. this._halfpitch = 0.0;
  58247. this._halfyaw = 0.0;
  58248. this._sinRoll = 0.0;
  58249. this._cosRoll = 0.0;
  58250. this._sinPitch = 0.0;
  58251. this._cosPitch = 0.0;
  58252. this._sinYaw = 0.0;
  58253. this._cosYaw = 0.0;
  58254. this._mustUnrotateFixedNormals = false;
  58255. this._minimum = BABYLON.Vector3.Zero();
  58256. this._maximum = BABYLON.Vector3.Zero();
  58257. this._minBbox = BABYLON.Vector3.Zero();
  58258. this._maxBbox = BABYLON.Vector3.Zero();
  58259. this._particlesIntersect = false;
  58260. this._depthSortFunction = function (p1, p2) {
  58261. return (p2.sqDistance - p1.sqDistance);
  58262. };
  58263. this._needs32Bits = false;
  58264. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58265. this._scaledPivot = BABYLON.Vector3.Zero();
  58266. this._particleHasParent = false;
  58267. this.name = name;
  58268. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58269. this._camera = scene.activeCamera;
  58270. this._pickable = options ? options.isPickable : false;
  58271. this._depthSort = options ? options.enableDepthSort : false;
  58272. this._particlesIntersect = options ? options.particleIntersection : false;
  58273. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58274. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58275. if (options && options.updatable) {
  58276. this._updatable = options.updatable;
  58277. }
  58278. else {
  58279. this._updatable = true;
  58280. }
  58281. if (this._pickable) {
  58282. this.pickedParticles = [];
  58283. }
  58284. if (this._depthSort) {
  58285. this.depthSortedParticles = [];
  58286. }
  58287. }
  58288. /**
  58289. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58290. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58291. * @returns the created mesh
  58292. */
  58293. SolidParticleSystem.prototype.buildMesh = function () {
  58294. if (this.nbParticles === 0) {
  58295. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58296. this.addShape(triangle, 1);
  58297. triangle.dispose();
  58298. }
  58299. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58300. this._positions32 = new Float32Array(this._positions);
  58301. this._uvs32 = new Float32Array(this._uvs);
  58302. this._colors32 = new Float32Array(this._colors);
  58303. if (this.recomputeNormals) {
  58304. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58305. }
  58306. this._normals32 = new Float32Array(this._normals);
  58307. this._fixedNormal32 = new Float32Array(this._normals);
  58308. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58309. this._unrotateFixedNormals();
  58310. }
  58311. var vertexData = new BABYLON.VertexData();
  58312. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58313. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58314. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58315. if (this._uvs32.length > 0) {
  58316. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58317. }
  58318. if (this._colors32.length > 0) {
  58319. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58320. }
  58321. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58322. vertexData.applyToMesh(mesh, this._updatable);
  58323. this.mesh = mesh;
  58324. this.mesh.isPickable = this._pickable;
  58325. // free memory
  58326. if (!this._depthSort) {
  58327. this._indices = null;
  58328. }
  58329. this._positions = null;
  58330. this._normals = null;
  58331. this._uvs = null;
  58332. this._colors = null;
  58333. if (!this._updatable) {
  58334. this.particles.length = 0;
  58335. }
  58336. return mesh;
  58337. };
  58338. /**
  58339. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58340. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58341. * Thus the particles generated from `digest()` have their property `position` set yet.
  58342. * @param mesh ( Mesh ) is the mesh to be digested
  58343. * @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
  58344. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58345. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58346. * @returns the current SPS
  58347. */
  58348. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58349. var size = (options && options.facetNb) || 1;
  58350. var number = (options && options.number) || 0;
  58351. var delta = (options && options.delta) || 0;
  58352. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58353. var meshInd = mesh.getIndices();
  58354. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58355. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58356. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58357. var f = 0; // facet counter
  58358. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58359. // compute size from number
  58360. if (number) {
  58361. number = (number > totalFacets) ? totalFacets : number;
  58362. size = Math.round(totalFacets / number);
  58363. delta = 0;
  58364. }
  58365. else {
  58366. size = (size > totalFacets) ? totalFacets : size;
  58367. }
  58368. var facetPos = []; // submesh positions
  58369. var facetInd = []; // submesh indices
  58370. var facetUV = []; // submesh UV
  58371. var facetCol = []; // submesh colors
  58372. var barycenter = BABYLON.Vector3.Zero();
  58373. var sizeO = size;
  58374. while (f < totalFacets) {
  58375. size = sizeO + Math.floor((1 + delta) * Math.random());
  58376. if (f > totalFacets - size) {
  58377. size = totalFacets - f;
  58378. }
  58379. // reset temp arrays
  58380. facetPos.length = 0;
  58381. facetInd.length = 0;
  58382. facetUV.length = 0;
  58383. facetCol.length = 0;
  58384. // iterate over "size" facets
  58385. var fi = 0;
  58386. for (var j = f * 3; j < (f + size) * 3; j++) {
  58387. facetInd.push(fi);
  58388. var i = meshInd[j];
  58389. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58390. if (meshUV) {
  58391. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58392. }
  58393. if (meshCol) {
  58394. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58395. }
  58396. fi++;
  58397. }
  58398. // create a model shape for each single particle
  58399. var idx = this.nbParticles;
  58400. var shape = this._posToShape(facetPos);
  58401. var shapeUV = this._uvsToShapeUV(facetUV);
  58402. // compute the barycenter of the shape
  58403. var v;
  58404. for (v = 0; v < shape.length; v++) {
  58405. barycenter.addInPlace(shape[v]);
  58406. }
  58407. barycenter.scaleInPlace(1 / shape.length);
  58408. // shift the shape from its barycenter to the origin
  58409. for (v = 0; v < shape.length; v++) {
  58410. shape[v].subtractInPlace(barycenter);
  58411. }
  58412. var bInfo;
  58413. if (this._particlesIntersect) {
  58414. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58415. }
  58416. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58417. // add the particle in the SPS
  58418. var currentPos = this._positions.length;
  58419. var currentInd = this._indices.length;
  58420. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58421. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58422. // initialize the particle position
  58423. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58424. this._index += shape.length;
  58425. idx++;
  58426. this.nbParticles++;
  58427. this._shapeCounter++;
  58428. f += size;
  58429. }
  58430. return this;
  58431. };
  58432. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58433. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58434. var index = 0;
  58435. var idx = 0;
  58436. for (var p = 0; p < this.particles.length; p++) {
  58437. this._particle = this.particles[p];
  58438. this._shape = this._particle._model._shape;
  58439. if (this._particle.rotationQuaternion) {
  58440. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58441. }
  58442. else {
  58443. this._yaw = this._particle.rotation.y;
  58444. this._pitch = this._particle.rotation.x;
  58445. this._roll = this._particle.rotation.z;
  58446. this._quaternionRotationYPR();
  58447. }
  58448. this._quaternionToRotationMatrix();
  58449. this._rotMatrix.invertToRef(this._invertMatrix);
  58450. for (var pt = 0; pt < this._shape.length; pt++) {
  58451. idx = index + pt * 3;
  58452. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58453. this._fixedNormal32[idx] = this._normal.x;
  58454. this._fixedNormal32[idx + 1] = this._normal.y;
  58455. this._fixedNormal32[idx + 2] = this._normal.z;
  58456. }
  58457. index = idx + 3;
  58458. }
  58459. };
  58460. //reset copy
  58461. SolidParticleSystem.prototype._resetCopy = function () {
  58462. this._copy.position.x = 0;
  58463. this._copy.position.y = 0;
  58464. this._copy.position.z = 0;
  58465. this._copy.rotation.x = 0;
  58466. this._copy.rotation.y = 0;
  58467. this._copy.rotation.z = 0;
  58468. this._copy.rotationQuaternion = null;
  58469. this._copy.scaling.x = 1.0;
  58470. this._copy.scaling.y = 1.0;
  58471. this._copy.scaling.z = 1.0;
  58472. this._copy.uvs.x = 0;
  58473. this._copy.uvs.y = 0;
  58474. this._copy.uvs.z = 1.0;
  58475. this._copy.uvs.w = 1.0;
  58476. this._copy.color = null;
  58477. this._copy.translateFromPivot = false;
  58478. };
  58479. // _meshBuilder : inserts the shape model in the global SPS mesh
  58480. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58481. var i;
  58482. var u = 0;
  58483. var c = 0;
  58484. var n = 0;
  58485. this._resetCopy();
  58486. if (options && options.positionFunction) { // call to custom positionFunction
  58487. options.positionFunction(this._copy, idx, idxInShape);
  58488. this._mustUnrotateFixedNormals = true;
  58489. }
  58490. if (this._copy.rotationQuaternion) {
  58491. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58492. }
  58493. else {
  58494. this._yaw = this._copy.rotation.y;
  58495. this._pitch = this._copy.rotation.x;
  58496. this._roll = this._copy.rotation.z;
  58497. this._quaternionRotationYPR();
  58498. }
  58499. this._quaternionToRotationMatrix();
  58500. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58501. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58502. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58503. if (this._copy.translateFromPivot) {
  58504. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58505. }
  58506. else {
  58507. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58508. }
  58509. for (i = 0; i < shape.length; i++) {
  58510. this._vertex.x = shape[i].x;
  58511. this._vertex.y = shape[i].y;
  58512. this._vertex.z = shape[i].z;
  58513. if (options && options.vertexFunction) {
  58514. options.vertexFunction(this._copy, this._vertex, i);
  58515. }
  58516. this._vertex.x *= this._copy.scaling.x;
  58517. this._vertex.y *= this._copy.scaling.y;
  58518. this._vertex.z *= this._copy.scaling.z;
  58519. this._vertex.x -= this._scaledPivot.x;
  58520. this._vertex.y -= this._scaledPivot.y;
  58521. this._vertex.z -= this._scaledPivot.z;
  58522. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58523. this._rotated.addInPlace(this._pivotBackTranslation);
  58524. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58525. if (meshUV) {
  58526. 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);
  58527. u += 2;
  58528. }
  58529. if (this._copy.color) {
  58530. this._color = this._copy.color;
  58531. }
  58532. else if (meshCol && meshCol[c] !== undefined) {
  58533. this._color.r = meshCol[c];
  58534. this._color.g = meshCol[c + 1];
  58535. this._color.b = meshCol[c + 2];
  58536. this._color.a = meshCol[c + 3];
  58537. }
  58538. else {
  58539. this._color.r = 1.0;
  58540. this._color.g = 1.0;
  58541. this._color.b = 1.0;
  58542. this._color.a = 1.0;
  58543. }
  58544. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58545. c += 4;
  58546. if (!this.recomputeNormals && meshNor) {
  58547. this._normal.x = meshNor[n];
  58548. this._normal.y = meshNor[n + 1];
  58549. this._normal.z = meshNor[n + 2];
  58550. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58551. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58552. n += 3;
  58553. }
  58554. }
  58555. for (i = 0; i < meshInd.length; i++) {
  58556. var current_ind = p + meshInd[i];
  58557. indices.push(current_ind);
  58558. if (current_ind > 65535) {
  58559. this._needs32Bits = true;
  58560. }
  58561. }
  58562. if (this._pickable) {
  58563. var nbfaces = meshInd.length / 3;
  58564. for (i = 0; i < nbfaces; i++) {
  58565. this.pickedParticles.push({ idx: idx, faceId: i });
  58566. }
  58567. }
  58568. if (this._depthSort) {
  58569. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58570. }
  58571. return this._copy;
  58572. };
  58573. // returns a shape array from positions array
  58574. SolidParticleSystem.prototype._posToShape = function (positions) {
  58575. var shape = [];
  58576. for (var i = 0; i < positions.length; i += 3) {
  58577. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58578. }
  58579. return shape;
  58580. };
  58581. // returns a shapeUV array from a Vector4 uvs
  58582. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58583. var shapeUV = [];
  58584. if (uvs) {
  58585. for (var i = 0; i < uvs.length; i++)
  58586. shapeUV.push(uvs[i]);
  58587. }
  58588. return shapeUV;
  58589. };
  58590. // adds a new particle object in the particles array
  58591. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58592. if (bInfo === void 0) { bInfo = null; }
  58593. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58594. this.particles.push(sp);
  58595. return sp;
  58596. };
  58597. /**
  58598. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58599. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58600. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58601. * @param nb (positive integer) the number of particles to be created from this model
  58602. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58603. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58604. * @returns the number of shapes in the system
  58605. */
  58606. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58607. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58608. var meshInd = mesh.getIndices();
  58609. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58610. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58611. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58612. var bbInfo;
  58613. if (this._particlesIntersect) {
  58614. bbInfo = mesh.getBoundingInfo();
  58615. }
  58616. var shape = this._posToShape(meshPos);
  58617. var shapeUV = this._uvsToShapeUV(meshUV);
  58618. var posfunc = options ? options.positionFunction : null;
  58619. var vtxfunc = options ? options.vertexFunction : null;
  58620. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58621. // particles
  58622. var sp;
  58623. var currentCopy;
  58624. var idx = this.nbParticles;
  58625. for (var i = 0; i < nb; i++) {
  58626. var currentPos = this._positions.length;
  58627. var currentInd = this._indices.length;
  58628. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58629. if (this._updatable) {
  58630. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58631. sp.position.copyFrom(currentCopy.position);
  58632. sp.rotation.copyFrom(currentCopy.rotation);
  58633. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58634. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58635. }
  58636. if (currentCopy.color && sp.color) {
  58637. sp.color.copyFrom(currentCopy.color);
  58638. }
  58639. sp.scaling.copyFrom(currentCopy.scaling);
  58640. sp.uvs.copyFrom(currentCopy.uvs);
  58641. }
  58642. this._index += shape.length;
  58643. idx++;
  58644. }
  58645. this.nbParticles += nb;
  58646. this._shapeCounter++;
  58647. return this._shapeCounter - 1;
  58648. };
  58649. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58650. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58651. this._resetCopy();
  58652. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58653. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58654. }
  58655. if (this._copy.rotationQuaternion) {
  58656. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58657. }
  58658. else {
  58659. this._yaw = this._copy.rotation.y;
  58660. this._pitch = this._copy.rotation.x;
  58661. this._roll = this._copy.rotation.z;
  58662. this._quaternionRotationYPR();
  58663. }
  58664. this._quaternionToRotationMatrix();
  58665. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58666. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58667. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58668. if (this._copy.translateFromPivot) {
  58669. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58670. }
  58671. else {
  58672. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58673. }
  58674. this._shape = particle._model._shape;
  58675. for (var pt = 0; pt < this._shape.length; pt++) {
  58676. this._vertex.x = this._shape[pt].x;
  58677. this._vertex.y = this._shape[pt].y;
  58678. this._vertex.z = this._shape[pt].z;
  58679. if (particle._model._vertexFunction) {
  58680. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58681. }
  58682. this._vertex.x *= this._copy.scaling.x;
  58683. this._vertex.y *= this._copy.scaling.y;
  58684. this._vertex.z *= this._copy.scaling.z;
  58685. this._vertex.x -= this._scaledPivot.x;
  58686. this._vertex.y -= this._scaledPivot.y;
  58687. this._vertex.z -= this._scaledPivot.z;
  58688. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58689. this._rotated.addInPlace(this._pivotBackTranslation);
  58690. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58691. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58692. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58693. }
  58694. particle.position.x = 0.0;
  58695. particle.position.y = 0.0;
  58696. particle.position.z = 0.0;
  58697. particle.rotation.x = 0.0;
  58698. particle.rotation.y = 0.0;
  58699. particle.rotation.z = 0.0;
  58700. particle.rotationQuaternion = null;
  58701. particle.scaling.x = 1.0;
  58702. particle.scaling.y = 1.0;
  58703. particle.scaling.z = 1.0;
  58704. particle.uvs.x = 0.0;
  58705. particle.uvs.y = 0.0;
  58706. particle.uvs.z = 1.0;
  58707. particle.uvs.w = 1.0;
  58708. particle.pivot.x = 0.0;
  58709. particle.pivot.y = 0.0;
  58710. particle.pivot.z = 0.0;
  58711. particle.translateFromPivot = false;
  58712. particle.parentId = null;
  58713. };
  58714. /**
  58715. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58716. * @returns the SPS.
  58717. */
  58718. SolidParticleSystem.prototype.rebuildMesh = function () {
  58719. for (var p = 0; p < this.particles.length; p++) {
  58720. this._rebuildParticle(this.particles[p]);
  58721. }
  58722. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58723. return this;
  58724. };
  58725. /**
  58726. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58727. * This method calls `updateParticle()` for each particle of the SPS.
  58728. * For an animated SPS, it is usually called within the render loop.
  58729. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58730. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58731. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58732. * @returns the SPS.
  58733. */
  58734. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58735. if (start === void 0) { start = 0; }
  58736. if (end === void 0) { end = this.nbParticles - 1; }
  58737. if (update === void 0) { update = true; }
  58738. if (!this._updatable) {
  58739. return this;
  58740. }
  58741. // custom beforeUpdate
  58742. this.beforeUpdateParticles(start, end, update);
  58743. this._cam_axisX.x = 1.0;
  58744. this._cam_axisX.y = 0.0;
  58745. this._cam_axisX.z = 0.0;
  58746. this._cam_axisY.x = 0.0;
  58747. this._cam_axisY.y = 1.0;
  58748. this._cam_axisY.z = 0.0;
  58749. this._cam_axisZ.x = 0.0;
  58750. this._cam_axisZ.y = 0.0;
  58751. this._cam_axisZ.z = 1.0;
  58752. // cases when the World Matrix is to be computed first
  58753. if (this.billboard || this._depthSort) {
  58754. this.mesh.computeWorldMatrix(true);
  58755. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58756. }
  58757. // if the particles will always face the camera
  58758. if (this.billboard) {
  58759. // compute the camera position and un-rotate it by the current mesh rotation
  58760. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58761. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58762. this._cam_axisZ.normalize();
  58763. // same for camera up vector extracted from the cam view matrix
  58764. var view = this._camera.getViewMatrix(true);
  58765. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58766. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58767. this._cam_axisY.normalize();
  58768. this._cam_axisX.normalize();
  58769. }
  58770. // if depthSort, compute the camera global position in the mesh local system
  58771. if (this._depthSort) {
  58772. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58773. }
  58774. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58775. var idx = 0; // current position index in the global array positions32
  58776. var index = 0; // position start index in the global array positions32 of the current particle
  58777. var colidx = 0; // current color index in the global array colors32
  58778. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58779. var uvidx = 0; // current uv index in the global array uvs32
  58780. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58781. var pt = 0; // current index in the particle model shape
  58782. if (this.mesh.isFacetDataEnabled) {
  58783. this._computeBoundingBox = true;
  58784. }
  58785. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58786. if (this._computeBoundingBox) {
  58787. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58788. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58789. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58790. }
  58791. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58792. if (this.mesh._boundingInfo) {
  58793. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58794. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58795. }
  58796. }
  58797. }
  58798. // particle loop
  58799. index = this.particles[start]._pos;
  58800. var vpos = (index / 3) | 0;
  58801. colorIndex = vpos * 4;
  58802. uvIndex = vpos * 2;
  58803. for (var p = start; p <= end; p++) {
  58804. this._particle = this.particles[p];
  58805. this._shape = this._particle._model._shape;
  58806. this._shapeUV = this._particle._model._shapeUV;
  58807. // call to custom user function to update the particle properties
  58808. this.updateParticle(this._particle);
  58809. // camera-particle distance for depth sorting
  58810. if (this._depthSort && this._depthSortParticles) {
  58811. var dsp = this.depthSortedParticles[p];
  58812. dsp.ind = this._particle._ind;
  58813. dsp.indicesLength = this._particle._model._indicesLength;
  58814. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58815. }
  58816. // skip the computations for inactive or already invisible particles
  58817. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58818. // increment indexes for the next particle
  58819. pt = this._shape.length;
  58820. index += pt * 3;
  58821. colorIndex += pt * 4;
  58822. uvIndex += pt * 2;
  58823. continue;
  58824. }
  58825. if (this._particle.isVisible) {
  58826. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58827. this._particleHasParent = (this._particle.parentId !== null);
  58828. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58829. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58830. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58831. // particle rotation matrix
  58832. if (this.billboard) {
  58833. this._particle.rotation.x = 0.0;
  58834. this._particle.rotation.y = 0.0;
  58835. }
  58836. if (this._computeParticleRotation || this.billboard) {
  58837. if (this._particle.rotationQuaternion) {
  58838. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58839. }
  58840. else {
  58841. this._yaw = this._particle.rotation.y;
  58842. this._pitch = this._particle.rotation.x;
  58843. this._roll = this._particle.rotation.z;
  58844. this._quaternionRotationYPR();
  58845. }
  58846. this._quaternionToRotationMatrix();
  58847. }
  58848. if (this._particleHasParent) {
  58849. this._parent = this.particles[this._particle.parentId];
  58850. 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];
  58851. 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];
  58852. 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];
  58853. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58854. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58855. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58856. if (this._computeParticleRotation || this.billboard) {
  58857. 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];
  58858. 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];
  58859. 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];
  58860. 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];
  58861. 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];
  58862. 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];
  58863. 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];
  58864. 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];
  58865. 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];
  58866. }
  58867. }
  58868. else {
  58869. this._particle._globalPosition.x = this._particle.position.x;
  58870. this._particle._globalPosition.y = this._particle.position.y;
  58871. this._particle._globalPosition.z = this._particle.position.z;
  58872. if (this._computeParticleRotation || this.billboard) {
  58873. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58874. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58875. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58876. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58877. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58878. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58879. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58880. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58881. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58882. }
  58883. }
  58884. if (this._particle.translateFromPivot) {
  58885. this._pivotBackTranslation.x = 0.0;
  58886. this._pivotBackTranslation.y = 0.0;
  58887. this._pivotBackTranslation.z = 0.0;
  58888. }
  58889. else {
  58890. this._pivotBackTranslation.x = this._scaledPivot.x;
  58891. this._pivotBackTranslation.y = this._scaledPivot.y;
  58892. this._pivotBackTranslation.z = this._scaledPivot.z;
  58893. }
  58894. // particle vertex loop
  58895. for (pt = 0; pt < this._shape.length; pt++) {
  58896. idx = index + pt * 3;
  58897. colidx = colorIndex + pt * 4;
  58898. uvidx = uvIndex + pt * 2;
  58899. this._vertex.x = this._shape[pt].x;
  58900. this._vertex.y = this._shape[pt].y;
  58901. this._vertex.z = this._shape[pt].z;
  58902. if (this._computeParticleVertex) {
  58903. this.updateParticleVertex(this._particle, this._vertex, pt);
  58904. }
  58905. // positions
  58906. this._vertex.x *= this._particle.scaling.x;
  58907. this._vertex.y *= this._particle.scaling.y;
  58908. this._vertex.z *= this._particle.scaling.z;
  58909. this._vertex.x -= this._scaledPivot.x;
  58910. this._vertex.y -= this._scaledPivot.y;
  58911. this._vertex.z -= this._scaledPivot.z;
  58912. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58913. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58914. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58915. this._rotated.x += this._pivotBackTranslation.x;
  58916. this._rotated.y += this._pivotBackTranslation.y;
  58917. this._rotated.z += this._pivotBackTranslation.z;
  58918. 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;
  58919. 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;
  58920. 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;
  58921. if (this._computeBoundingBox) {
  58922. if (this._positions32[idx] < this._minimum.x) {
  58923. this._minimum.x = this._positions32[idx];
  58924. }
  58925. if (this._positions32[idx] > this._maximum.x) {
  58926. this._maximum.x = this._positions32[idx];
  58927. }
  58928. if (this._positions32[idx + 1] < this._minimum.y) {
  58929. this._minimum.y = this._positions32[idx + 1];
  58930. }
  58931. if (this._positions32[idx + 1] > this._maximum.y) {
  58932. this._maximum.y = this._positions32[idx + 1];
  58933. }
  58934. if (this._positions32[idx + 2] < this._minimum.z) {
  58935. this._minimum.z = this._positions32[idx + 2];
  58936. }
  58937. if (this._positions32[idx + 2] > this._maximum.z) {
  58938. this._maximum.z = this._positions32[idx + 2];
  58939. }
  58940. }
  58941. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58942. if (!this._computeParticleVertex) {
  58943. this._normal.x = this._fixedNormal32[idx];
  58944. this._normal.y = this._fixedNormal32[idx + 1];
  58945. this._normal.z = this._fixedNormal32[idx + 2];
  58946. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58947. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58948. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58949. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58950. 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;
  58951. 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;
  58952. }
  58953. if (this._computeParticleColor && this._particle.color) {
  58954. this._colors32[colidx] = this._particle.color.r;
  58955. this._colors32[colidx + 1] = this._particle.color.g;
  58956. this._colors32[colidx + 2] = this._particle.color.b;
  58957. this._colors32[colidx + 3] = this._particle.color.a;
  58958. }
  58959. if (this._computeParticleTexture) {
  58960. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58961. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58962. }
  58963. }
  58964. }
  58965. // particle just set invisible : scaled to zero and positioned at the origin
  58966. else {
  58967. this._particle._stillInvisible = true; // mark the particle as invisible
  58968. for (pt = 0; pt < this._shape.length; pt++) {
  58969. idx = index + pt * 3;
  58970. colidx = colorIndex + pt * 4;
  58971. uvidx = uvIndex + pt * 2;
  58972. this._positions32[idx] = 0.0;
  58973. this._positions32[idx + 1] = 0.0;
  58974. this._positions32[idx + 2] = 0.0;
  58975. this._normals32[idx] = 0.0;
  58976. this._normals32[idx + 1] = 0.0;
  58977. this._normals32[idx + 2] = 0.0;
  58978. if (this._computeParticleColor && this._particle.color) {
  58979. this._colors32[colidx] = this._particle.color.r;
  58980. this._colors32[colidx + 1] = this._particle.color.g;
  58981. this._colors32[colidx + 2] = this._particle.color.b;
  58982. this._colors32[colidx + 3] = this._particle.color.a;
  58983. }
  58984. if (this._computeParticleTexture) {
  58985. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58986. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58987. }
  58988. }
  58989. }
  58990. // if the particle intersections must be computed : update the bbInfo
  58991. if (this._particlesIntersect) {
  58992. var bInfo = this._particle._boundingInfo;
  58993. var bBox = bInfo.boundingBox;
  58994. var bSphere = bInfo.boundingSphere;
  58995. if (!this._bSphereOnly) {
  58996. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58997. for (var b = 0; b < bBox.vectors.length; b++) {
  58998. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58999. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59000. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59001. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59002. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59003. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59004. 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;
  59005. 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;
  59006. 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;
  59007. }
  59008. bBox._update(this.mesh._worldMatrix);
  59009. }
  59010. // place and scale the particle bouding sphere in the SPS local system, then update it
  59011. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59012. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59013. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59014. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59015. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59016. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59017. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59018. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59019. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59020. 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));
  59021. bSphere._update(this.mesh._worldMatrix);
  59022. }
  59023. // increment indexes for the next particle
  59024. index = idx + 3;
  59025. colorIndex = colidx + 4;
  59026. uvIndex = uvidx + 2;
  59027. }
  59028. // if the VBO must be updated
  59029. if (update) {
  59030. if (this._computeParticleColor) {
  59031. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59032. }
  59033. if (this._computeParticleTexture) {
  59034. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59035. }
  59036. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59037. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59038. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59039. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59040. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59041. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59042. for (var i = 0; i < this._normals32.length; i++) {
  59043. this._fixedNormal32[i] = this._normals32[i];
  59044. }
  59045. }
  59046. if (!this.mesh.areNormalsFrozen) {
  59047. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59048. }
  59049. }
  59050. if (this._depthSort && this._depthSortParticles) {
  59051. this.depthSortedParticles.sort(this._depthSortFunction);
  59052. var dspl = this.depthSortedParticles.length;
  59053. var sorted = 0;
  59054. var lind = 0;
  59055. var sind = 0;
  59056. var sid = 0;
  59057. for (sorted = 0; sorted < dspl; sorted++) {
  59058. lind = this.depthSortedParticles[sorted].indicesLength;
  59059. sind = this.depthSortedParticles[sorted].ind;
  59060. for (var i = 0; i < lind; i++) {
  59061. this._indices32[sid] = this._indices[sind + i];
  59062. sid++;
  59063. }
  59064. }
  59065. this.mesh.updateIndices(this._indices32);
  59066. }
  59067. }
  59068. if (this._computeBoundingBox) {
  59069. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59070. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59071. }
  59072. this.afterUpdateParticles(start, end, update);
  59073. return this;
  59074. };
  59075. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59076. this._halfroll = this._roll * 0.5;
  59077. this._halfpitch = this._pitch * 0.5;
  59078. this._halfyaw = this._yaw * 0.5;
  59079. this._sinRoll = Math.sin(this._halfroll);
  59080. this._cosRoll = Math.cos(this._halfroll);
  59081. this._sinPitch = Math.sin(this._halfpitch);
  59082. this._cosPitch = Math.cos(this._halfpitch);
  59083. this._sinYaw = Math.sin(this._halfyaw);
  59084. this._cosYaw = Math.cos(this._halfyaw);
  59085. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59086. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59087. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59088. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59089. };
  59090. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59091. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59092. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59093. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59094. this._rotMatrix.m[3] = 0;
  59095. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59096. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59097. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59098. this._rotMatrix.m[7] = 0;
  59099. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59100. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59101. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59102. this._rotMatrix.m[11] = 0;
  59103. this._rotMatrix.m[12] = 0;
  59104. this._rotMatrix.m[13] = 0;
  59105. this._rotMatrix.m[14] = 0;
  59106. this._rotMatrix.m[15] = 1.0;
  59107. };
  59108. /**
  59109. * Disposes the SPS.
  59110. */
  59111. SolidParticleSystem.prototype.dispose = function () {
  59112. this.mesh.dispose();
  59113. this.vars = null;
  59114. // drop references to internal big arrays for the GC
  59115. this._positions = null;
  59116. this._indices = null;
  59117. this._normals = null;
  59118. this._uvs = null;
  59119. this._colors = null;
  59120. this._indices32 = null;
  59121. this._positions32 = null;
  59122. this._normals32 = null;
  59123. this._fixedNormal32 = null;
  59124. this._uvs32 = null;
  59125. this._colors32 = null;
  59126. this.pickedParticles = null;
  59127. };
  59128. /**
  59129. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59130. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59131. * @returns the SPS.
  59132. */
  59133. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59134. if (!this._isVisibilityBoxLocked) {
  59135. this.mesh.refreshBoundingInfo();
  59136. }
  59137. return this;
  59138. };
  59139. /**
  59140. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59141. * @param size the size (float) of the visibility box
  59142. * note : this doesn't lock the SPS mesh bounding box.
  59143. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59144. */
  59145. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59146. var vis = size / 2;
  59147. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59148. };
  59149. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59150. /**
  59151. * Gets whether the SPS as always visible or not
  59152. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59153. */
  59154. get: function () {
  59155. return this._alwaysVisible;
  59156. },
  59157. /**
  59158. * Sets the SPS as always visible or not
  59159. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59160. */
  59161. set: function (val) {
  59162. this._alwaysVisible = val;
  59163. this.mesh.alwaysSelectAsActiveMesh = val;
  59164. },
  59165. enumerable: true,
  59166. configurable: true
  59167. });
  59168. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59169. /**
  59170. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59171. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59172. */
  59173. get: function () {
  59174. return this._isVisibilityBoxLocked;
  59175. },
  59176. /**
  59177. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59178. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59179. */
  59180. set: function (val) {
  59181. this._isVisibilityBoxLocked = val;
  59182. var boundingInfo = this.mesh.getBoundingInfo();
  59183. boundingInfo.isLocked = val;
  59184. },
  59185. enumerable: true,
  59186. configurable: true
  59187. });
  59188. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59189. /**
  59190. * Gets if `setParticles()` computes the particle rotations or not.
  59191. * Default value : true. The SPS is faster when it's set to false.
  59192. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59193. */
  59194. get: function () {
  59195. return this._computeParticleRotation;
  59196. },
  59197. /**
  59198. * Tells to `setParticles()` to compute the particle rotations or not.
  59199. * Default value : true. The SPS is faster when it's set to false.
  59200. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59201. */
  59202. set: function (val) {
  59203. this._computeParticleRotation = val;
  59204. },
  59205. enumerable: true,
  59206. configurable: true
  59207. });
  59208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59209. /**
  59210. * Gets if `setParticles()` computes the particle colors or not.
  59211. * Default value : true. The SPS is faster when it's set to false.
  59212. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59213. */
  59214. get: function () {
  59215. return this._computeParticleColor;
  59216. },
  59217. /**
  59218. * Tells to `setParticles()` to compute the particle colors or not.
  59219. * Default value : true. The SPS is faster when it's set to false.
  59220. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59221. */
  59222. set: function (val) {
  59223. this._computeParticleColor = val;
  59224. },
  59225. enumerable: true,
  59226. configurable: true
  59227. });
  59228. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59229. /**
  59230. * Gets if `setParticles()` computes the particle textures or not.
  59231. * Default value : true. The SPS is faster when it's set to false.
  59232. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59233. */
  59234. get: function () {
  59235. return this._computeParticleTexture;
  59236. },
  59237. set: function (val) {
  59238. this._computeParticleTexture = val;
  59239. },
  59240. enumerable: true,
  59241. configurable: true
  59242. });
  59243. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59244. /**
  59245. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59246. * Default value : false. The SPS is faster when it's set to false.
  59247. * Note : the particle custom vertex positions aren't stored values.
  59248. */
  59249. get: function () {
  59250. return this._computeParticleVertex;
  59251. },
  59252. /**
  59253. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59254. * Default value : false. The SPS is faster when it's set to false.
  59255. * Note : the particle custom vertex positions aren't stored values.
  59256. */
  59257. set: function (val) {
  59258. this._computeParticleVertex = val;
  59259. },
  59260. enumerable: true,
  59261. configurable: true
  59262. });
  59263. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59264. /**
  59265. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59266. */
  59267. get: function () {
  59268. return this._computeBoundingBox;
  59269. },
  59270. /**
  59271. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59272. */
  59273. set: function (val) {
  59274. this._computeBoundingBox = val;
  59275. },
  59276. enumerable: true,
  59277. configurable: true
  59278. });
  59279. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59280. /**
  59281. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59282. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59283. * Default : `true`
  59284. */
  59285. get: function () {
  59286. return this._depthSortParticles;
  59287. },
  59288. /**
  59289. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59290. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59291. * Default : `true`
  59292. */
  59293. set: function (val) {
  59294. this._depthSortParticles = val;
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. // =======================================================================
  59300. // Particle behavior logic
  59301. // these following methods may be overwritten by the user to fit his needs
  59302. /**
  59303. * This function does nothing. It may be overwritten to set all the particle first values.
  59304. * The SPS doesn't call this function, you may have to call it by your own.
  59305. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59306. */
  59307. SolidParticleSystem.prototype.initParticles = function () {
  59308. };
  59309. /**
  59310. * This function does nothing. It may be overwritten to recycle a particle.
  59311. * The SPS doesn't call this function, you may have to call it by your own.
  59312. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59313. * @param particle The particle to recycle
  59314. * @returns the recycled particle
  59315. */
  59316. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59317. return particle;
  59318. };
  59319. /**
  59320. * Updates a particle : this function should be overwritten by the user.
  59321. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59322. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59323. * @example : just set a particle position or velocity and recycle conditions
  59324. * @param particle The particle to update
  59325. * @returns the updated particle
  59326. */
  59327. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59328. return particle;
  59329. };
  59330. /**
  59331. * Updates a vertex of a particle : it can be overwritten by the user.
  59332. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59333. * @param particle the current particle
  59334. * @param vertex the current index of the current particle
  59335. * @param pt the index of the current vertex in the particle shape
  59336. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59337. * @example : just set a vertex particle position
  59338. * @returns the updated vertex
  59339. */
  59340. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59341. return vertex;
  59342. };
  59343. /**
  59344. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59345. * This does nothing and may be overwritten by the user.
  59346. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59347. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59348. * @param update the boolean update value actually passed to setParticles()
  59349. */
  59350. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59351. };
  59352. /**
  59353. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59354. * This will be passed three parameters.
  59355. * This does nothing and may be overwritten by the user.
  59356. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59357. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59358. * @param update the boolean update value actually passed to setParticles()
  59359. */
  59360. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59361. };
  59362. return SolidParticleSystem;
  59363. }());
  59364. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59365. })(BABYLON || (BABYLON = {}));
  59366. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59367. var BABYLON;
  59368. (function (BABYLON) {
  59369. var ShaderMaterial = /** @class */ (function (_super) {
  59370. __extends(ShaderMaterial, _super);
  59371. function ShaderMaterial(name, scene, shaderPath, options) {
  59372. var _this = _super.call(this, name, scene) || this;
  59373. _this._textures = {};
  59374. _this._textureArrays = {};
  59375. _this._floats = {};
  59376. _this._ints = {};
  59377. _this._floatsArrays = {};
  59378. _this._colors3 = {};
  59379. _this._colors3Arrays = {};
  59380. _this._colors4 = {};
  59381. _this._vectors2 = {};
  59382. _this._vectors3 = {};
  59383. _this._vectors4 = {};
  59384. _this._matrices = {};
  59385. _this._matrices3x3 = {};
  59386. _this._matrices2x2 = {};
  59387. _this._vectors2Arrays = {};
  59388. _this._vectors3Arrays = {};
  59389. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59390. _this._shaderPath = shaderPath;
  59391. options.needAlphaBlending = options.needAlphaBlending || false;
  59392. options.needAlphaTesting = options.needAlphaTesting || false;
  59393. options.attributes = options.attributes || ["position", "normal", "uv"];
  59394. options.uniforms = options.uniforms || ["worldViewProjection"];
  59395. options.uniformBuffers = options.uniformBuffers || [];
  59396. options.samplers = options.samplers || [];
  59397. options.defines = options.defines || [];
  59398. _this._options = options;
  59399. return _this;
  59400. }
  59401. ShaderMaterial.prototype.getClassName = function () {
  59402. return "ShaderMaterial";
  59403. };
  59404. ShaderMaterial.prototype.needAlphaBlending = function () {
  59405. return this._options.needAlphaBlending;
  59406. };
  59407. ShaderMaterial.prototype.needAlphaTesting = function () {
  59408. return this._options.needAlphaTesting;
  59409. };
  59410. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59411. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59412. this._options.uniforms.push(uniformName);
  59413. }
  59414. };
  59415. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59416. if (this._options.samplers.indexOf(name) === -1) {
  59417. this._options.samplers.push(name);
  59418. }
  59419. this._textures[name] = texture;
  59420. return this;
  59421. };
  59422. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59423. if (this._options.samplers.indexOf(name) === -1) {
  59424. this._options.samplers.push(name);
  59425. }
  59426. this._checkUniform(name);
  59427. this._textureArrays[name] = textures;
  59428. return this;
  59429. };
  59430. ShaderMaterial.prototype.setFloat = function (name, value) {
  59431. this._checkUniform(name);
  59432. this._floats[name] = value;
  59433. return this;
  59434. };
  59435. ShaderMaterial.prototype.setInt = function (name, value) {
  59436. this._checkUniform(name);
  59437. this._ints[name] = value;
  59438. return this;
  59439. };
  59440. ShaderMaterial.prototype.setFloats = function (name, value) {
  59441. this._checkUniform(name);
  59442. this._floatsArrays[name] = value;
  59443. return this;
  59444. };
  59445. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59446. this._checkUniform(name);
  59447. this._colors3[name] = value;
  59448. return this;
  59449. };
  59450. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59451. this._checkUniform(name);
  59452. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59453. color.toArray(arr, arr.length);
  59454. return arr;
  59455. }, []);
  59456. return this;
  59457. };
  59458. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59459. this._checkUniform(name);
  59460. this._colors4[name] = value;
  59461. return this;
  59462. };
  59463. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59464. this._checkUniform(name);
  59465. this._vectors2[name] = value;
  59466. return this;
  59467. };
  59468. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59469. this._checkUniform(name);
  59470. this._vectors3[name] = value;
  59471. return this;
  59472. };
  59473. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59474. this._checkUniform(name);
  59475. this._vectors4[name] = value;
  59476. return this;
  59477. };
  59478. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59479. this._checkUniform(name);
  59480. this._matrices[name] = value;
  59481. return this;
  59482. };
  59483. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59484. this._checkUniform(name);
  59485. this._matrices3x3[name] = value;
  59486. return this;
  59487. };
  59488. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59489. this._checkUniform(name);
  59490. this._matrices2x2[name] = value;
  59491. return this;
  59492. };
  59493. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59494. this._checkUniform(name);
  59495. this._vectors2Arrays[name] = value;
  59496. return this;
  59497. };
  59498. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59499. this._checkUniform(name);
  59500. this._vectors3Arrays[name] = value;
  59501. return this;
  59502. };
  59503. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59504. if (!mesh) {
  59505. return true;
  59506. }
  59507. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59508. return false;
  59509. }
  59510. return false;
  59511. };
  59512. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59513. var scene = this.getScene();
  59514. var engine = scene.getEngine();
  59515. if (!this.checkReadyOnEveryCall) {
  59516. if (this._renderId === scene.getRenderId()) {
  59517. if (this._checkCache(scene, mesh, useInstances)) {
  59518. return true;
  59519. }
  59520. }
  59521. }
  59522. // Instances
  59523. var defines = [];
  59524. var attribs = [];
  59525. var fallbacks = new BABYLON.EffectFallbacks();
  59526. if (useInstances) {
  59527. defines.push("#define INSTANCES");
  59528. }
  59529. for (var index = 0; index < this._options.defines.length; index++) {
  59530. defines.push(this._options.defines[index]);
  59531. }
  59532. for (var index = 0; index < this._options.attributes.length; index++) {
  59533. attribs.push(this._options.attributes[index]);
  59534. }
  59535. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59536. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59537. defines.push("#define VERTEXCOLOR");
  59538. }
  59539. // Bones
  59540. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59543. if (mesh.numBoneInfluencers > 4) {
  59544. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59545. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59546. }
  59547. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59548. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59549. fallbacks.addCPUSkinningFallback(0, mesh);
  59550. if (this._options.uniforms.indexOf("mBones") === -1) {
  59551. this._options.uniforms.push("mBones");
  59552. }
  59553. }
  59554. else {
  59555. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59556. }
  59557. // Textures
  59558. for (var name in this._textures) {
  59559. if (!this._textures[name].isReady()) {
  59560. return false;
  59561. }
  59562. }
  59563. // Alpha test
  59564. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59565. defines.push("#define ALPHATEST");
  59566. }
  59567. var previousEffect = this._effect;
  59568. var join = defines.join("\n");
  59569. this._effect = engine.createEffect(this._shaderPath, {
  59570. attributes: attribs,
  59571. uniformsNames: this._options.uniforms,
  59572. uniformBuffersNames: this._options.uniformBuffers,
  59573. samplers: this._options.samplers,
  59574. defines: join,
  59575. fallbacks: fallbacks,
  59576. onCompiled: this.onCompiled,
  59577. onError: this.onError
  59578. }, engine);
  59579. if (!this._effect.isReady()) {
  59580. return false;
  59581. }
  59582. if (previousEffect !== this._effect) {
  59583. scene.resetCachedMaterial();
  59584. }
  59585. this._renderId = scene.getRenderId();
  59586. return true;
  59587. };
  59588. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59589. var scene = this.getScene();
  59590. if (!this._effect) {
  59591. return;
  59592. }
  59593. if (this._options.uniforms.indexOf("world") !== -1) {
  59594. this._effect.setMatrix("world", world);
  59595. }
  59596. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59597. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59598. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59599. }
  59600. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59601. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59602. }
  59603. };
  59604. ShaderMaterial.prototype.bind = function (world, mesh) {
  59605. // Std values
  59606. this.bindOnlyWorldMatrix(world);
  59607. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59608. if (this._options.uniforms.indexOf("view") !== -1) {
  59609. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59610. }
  59611. if (this._options.uniforms.indexOf("projection") !== -1) {
  59612. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59613. }
  59614. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59615. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59616. }
  59617. // Bones
  59618. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59619. var name;
  59620. // Texture
  59621. for (name in this._textures) {
  59622. this._effect.setTexture(name, this._textures[name]);
  59623. }
  59624. // Texture arrays
  59625. for (name in this._textureArrays) {
  59626. this._effect.setTextureArray(name, this._textureArrays[name]);
  59627. }
  59628. // Int
  59629. for (name in this._ints) {
  59630. this._effect.setInt(name, this._ints[name]);
  59631. }
  59632. // Float
  59633. for (name in this._floats) {
  59634. this._effect.setFloat(name, this._floats[name]);
  59635. }
  59636. // Floats
  59637. for (name in this._floatsArrays) {
  59638. this._effect.setArray(name, this._floatsArrays[name]);
  59639. }
  59640. // Color3
  59641. for (name in this._colors3) {
  59642. this._effect.setColor3(name, this._colors3[name]);
  59643. }
  59644. for (name in this._colors3Arrays) {
  59645. this._effect.setArray3(name, this._colors3Arrays[name]);
  59646. }
  59647. // Color4
  59648. for (name in this._colors4) {
  59649. var color = this._colors4[name];
  59650. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59651. }
  59652. // Vector2
  59653. for (name in this._vectors2) {
  59654. this._effect.setVector2(name, this._vectors2[name]);
  59655. }
  59656. // Vector3
  59657. for (name in this._vectors3) {
  59658. this._effect.setVector3(name, this._vectors3[name]);
  59659. }
  59660. // Vector4
  59661. for (name in this._vectors4) {
  59662. this._effect.setVector4(name, this._vectors4[name]);
  59663. }
  59664. // Matrix
  59665. for (name in this._matrices) {
  59666. this._effect.setMatrix(name, this._matrices[name]);
  59667. }
  59668. // Matrix 3x3
  59669. for (name in this._matrices3x3) {
  59670. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59671. }
  59672. // Matrix 2x2
  59673. for (name in this._matrices2x2) {
  59674. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59675. }
  59676. // Vector2Array
  59677. for (name in this._vectors2Arrays) {
  59678. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59679. }
  59680. // Vector3Array
  59681. for (name in this._vectors3Arrays) {
  59682. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59683. }
  59684. }
  59685. this._afterBind(mesh);
  59686. };
  59687. ShaderMaterial.prototype.getActiveTextures = function () {
  59688. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59689. for (var name in this._textures) {
  59690. activeTextures.push(this._textures[name]);
  59691. }
  59692. for (var name in this._textureArrays) {
  59693. var array = this._textureArrays[name];
  59694. for (var index = 0; index < array.length; index++) {
  59695. activeTextures.push(array[index]);
  59696. }
  59697. }
  59698. return activeTextures;
  59699. };
  59700. ShaderMaterial.prototype.hasTexture = function (texture) {
  59701. if (_super.prototype.hasTexture.call(this, texture)) {
  59702. return true;
  59703. }
  59704. for (var name in this._textures) {
  59705. if (this._textures[name] === texture) {
  59706. return true;
  59707. }
  59708. }
  59709. for (var name in this._textureArrays) {
  59710. var array = this._textureArrays[name];
  59711. for (var index = 0; index < array.length; index++) {
  59712. if (array[index] === texture) {
  59713. return true;
  59714. }
  59715. }
  59716. }
  59717. return false;
  59718. };
  59719. ShaderMaterial.prototype.clone = function (name) {
  59720. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59721. return newShaderMaterial;
  59722. };
  59723. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59724. if (forceDisposeTextures) {
  59725. var name;
  59726. for (name in this._textures) {
  59727. this._textures[name].dispose();
  59728. }
  59729. for (name in this._textureArrays) {
  59730. var array = this._textureArrays[name];
  59731. for (var index = 0; index < array.length; index++) {
  59732. array[index].dispose();
  59733. }
  59734. }
  59735. }
  59736. this._textures = {};
  59737. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59738. };
  59739. ShaderMaterial.prototype.serialize = function () {
  59740. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59741. serializationObject.customType = "BABYLON.ShaderMaterial";
  59742. serializationObject.options = this._options;
  59743. serializationObject.shaderPath = this._shaderPath;
  59744. var name;
  59745. // Texture
  59746. serializationObject.textures = {};
  59747. for (name in this._textures) {
  59748. serializationObject.textures[name] = this._textures[name].serialize();
  59749. }
  59750. // Texture arrays
  59751. serializationObject.textureArrays = {};
  59752. for (name in this._textureArrays) {
  59753. serializationObject.textureArrays[name] = [];
  59754. var array = this._textureArrays[name];
  59755. for (var index = 0; index < array.length; index++) {
  59756. serializationObject.textureArrays[name].push(array[index].serialize());
  59757. }
  59758. }
  59759. // Float
  59760. serializationObject.floats = {};
  59761. for (name in this._floats) {
  59762. serializationObject.floats[name] = this._floats[name];
  59763. }
  59764. // Float s
  59765. serializationObject.FloatArrays = {};
  59766. for (name in this._floatsArrays) {
  59767. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59768. }
  59769. // Color3
  59770. serializationObject.colors3 = {};
  59771. for (name in this._colors3) {
  59772. serializationObject.colors3[name] = this._colors3[name].asArray();
  59773. }
  59774. // Color3 array
  59775. serializationObject.colors3Arrays = {};
  59776. for (name in this._colors3Arrays) {
  59777. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59778. }
  59779. // Color4
  59780. serializationObject.colors4 = {};
  59781. for (name in this._colors4) {
  59782. serializationObject.colors4[name] = this._colors4[name].asArray();
  59783. }
  59784. // Vector2
  59785. serializationObject.vectors2 = {};
  59786. for (name in this._vectors2) {
  59787. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59788. }
  59789. // Vector3
  59790. serializationObject.vectors3 = {};
  59791. for (name in this._vectors3) {
  59792. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59793. }
  59794. // Vector4
  59795. serializationObject.vectors4 = {};
  59796. for (name in this._vectors4) {
  59797. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59798. }
  59799. // Matrix
  59800. serializationObject.matrices = {};
  59801. for (name in this._matrices) {
  59802. serializationObject.matrices[name] = this._matrices[name].asArray();
  59803. }
  59804. // Matrix 3x3
  59805. serializationObject.matrices3x3 = {};
  59806. for (name in this._matrices3x3) {
  59807. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59808. }
  59809. // Matrix 2x2
  59810. serializationObject.matrices2x2 = {};
  59811. for (name in this._matrices2x2) {
  59812. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59813. }
  59814. // Vector2Array
  59815. serializationObject.vectors2Arrays = {};
  59816. for (name in this._vectors2Arrays) {
  59817. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59818. }
  59819. // Vector3Array
  59820. serializationObject.vectors3Arrays = {};
  59821. for (name in this._vectors3Arrays) {
  59822. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59823. }
  59824. return serializationObject;
  59825. };
  59826. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59827. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59828. var name;
  59829. // Texture
  59830. for (name in source.textures) {
  59831. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59832. }
  59833. // Texture arrays
  59834. for (name in source.textureArrays) {
  59835. var array = source.textureArrays[name];
  59836. var textureArray = new Array();
  59837. for (var index = 0; index < array.length; index++) {
  59838. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59839. }
  59840. material.setTextureArray(name, textureArray);
  59841. }
  59842. // Float
  59843. for (name in source.floats) {
  59844. material.setFloat(name, source.floats[name]);
  59845. }
  59846. // Float s
  59847. for (name in source.floatsArrays) {
  59848. material.setFloats(name, source.floatsArrays[name]);
  59849. }
  59850. // Color3
  59851. for (name in source.colors3) {
  59852. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59853. }
  59854. // Color3 arrays
  59855. for (name in source.colors3Arrays) {
  59856. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59857. if (i % 3 === 0) {
  59858. arr.push([num]);
  59859. }
  59860. else {
  59861. arr[arr.length - 1].push(num);
  59862. }
  59863. return arr;
  59864. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59865. material.setColor3Array(name, colors);
  59866. }
  59867. // Color4
  59868. for (name in source.colors4) {
  59869. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59870. }
  59871. // Vector2
  59872. for (name in source.vectors2) {
  59873. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59874. }
  59875. // Vector3
  59876. for (name in source.vectors3) {
  59877. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59878. }
  59879. // Vector4
  59880. for (name in source.vectors4) {
  59881. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59882. }
  59883. // Matrix
  59884. for (name in source.matrices) {
  59885. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59886. }
  59887. // Matrix 3x3
  59888. for (name in source.matrices3x3) {
  59889. material.setMatrix3x3(name, source.matrices3x3[name]);
  59890. }
  59891. // Matrix 2x2
  59892. for (name in source.matrices2x2) {
  59893. material.setMatrix2x2(name, source.matrices2x2[name]);
  59894. }
  59895. // Vector2Array
  59896. for (name in source.vectors2Arrays) {
  59897. material.setArray2(name, source.vectors2Arrays[name]);
  59898. }
  59899. // Vector3Array
  59900. for (name in source.vectors3Arrays) {
  59901. material.setArray3(name, source.vectors3Arrays[name]);
  59902. }
  59903. return material;
  59904. };
  59905. return ShaderMaterial;
  59906. }(BABYLON.Material));
  59907. BABYLON.ShaderMaterial = ShaderMaterial;
  59908. })(BABYLON || (BABYLON = {}));
  59909. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59910. var BABYLON;
  59911. (function (BABYLON) {
  59912. var GroundMesh = /** @class */ (function (_super) {
  59913. __extends(GroundMesh, _super);
  59914. function GroundMesh(name, scene) {
  59915. var _this = _super.call(this, name, scene) || this;
  59916. _this.generateOctree = false;
  59917. return _this;
  59918. }
  59919. GroundMesh.prototype.getClassName = function () {
  59920. return "GroundMesh";
  59921. };
  59922. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59923. get: function () {
  59924. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59930. get: function () {
  59931. return this._subdivisionsX;
  59932. },
  59933. enumerable: true,
  59934. configurable: true
  59935. });
  59936. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59937. get: function () {
  59938. return this._subdivisionsY;
  59939. },
  59940. enumerable: true,
  59941. configurable: true
  59942. });
  59943. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59944. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59945. this._subdivisionsX = chunksCount;
  59946. this._subdivisionsY = chunksCount;
  59947. this.subdivide(chunksCount);
  59948. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59949. };
  59950. /**
  59951. * Returns a height (y) value in the Worl system :
  59952. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59953. * Returns the ground y position if (x, z) are outside the ground surface.
  59954. */
  59955. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59956. var world = this.getWorldMatrix();
  59957. var invMat = BABYLON.Tmp.Matrix[5];
  59958. world.invertToRef(invMat);
  59959. var tmpVect = BABYLON.Tmp.Vector3[8];
  59960. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59961. x = tmpVect.x;
  59962. z = tmpVect.z;
  59963. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59964. return this.position.y;
  59965. }
  59966. if (!this._heightQuads || this._heightQuads.length == 0) {
  59967. this._initHeightQuads();
  59968. this._computeHeightQuads();
  59969. }
  59970. var facet = this._getFacetAt(x, z);
  59971. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59972. // return y in the World system
  59973. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59974. return tmpVect.y;
  59975. };
  59976. /**
  59977. * Returns a normalized vector (Vector3) orthogonal to the ground
  59978. * at the ground coordinates (x, z) expressed in the World system.
  59979. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59980. */
  59981. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59982. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59983. this.getNormalAtCoordinatesToRef(x, z, normal);
  59984. return normal;
  59985. };
  59986. /**
  59987. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59988. * at the ground coordinates (x, z) expressed in the World system.
  59989. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59990. * Returns the GroundMesh.
  59991. */
  59992. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59993. var world = this.getWorldMatrix();
  59994. var tmpMat = BABYLON.Tmp.Matrix[5];
  59995. world.invertToRef(tmpMat);
  59996. var tmpVect = BABYLON.Tmp.Vector3[8];
  59997. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59998. x = tmpVect.x;
  59999. z = tmpVect.z;
  60000. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60001. return this;
  60002. }
  60003. if (!this._heightQuads || this._heightQuads.length == 0) {
  60004. this._initHeightQuads();
  60005. this._computeHeightQuads();
  60006. }
  60007. var facet = this._getFacetAt(x, z);
  60008. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60009. return this;
  60010. };
  60011. /**
  60012. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60013. * if the ground has been updated.
  60014. * This can be used in the render loop.
  60015. * Returns the GroundMesh.
  60016. */
  60017. GroundMesh.prototype.updateCoordinateHeights = function () {
  60018. if (!this._heightQuads || this._heightQuads.length == 0) {
  60019. this._initHeightQuads();
  60020. }
  60021. this._computeHeightQuads();
  60022. return this;
  60023. };
  60024. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60025. GroundMesh.prototype._getFacetAt = function (x, z) {
  60026. // retrieve col and row from x, z coordinates in the ground local system
  60027. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60028. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60029. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60030. var facet;
  60031. if (z < quad.slope.x * x + quad.slope.y) {
  60032. facet = quad.facet1;
  60033. }
  60034. else {
  60035. facet = quad.facet2;
  60036. }
  60037. return facet;
  60038. };
  60039. // Creates and populates the heightMap array with "facet" elements :
  60040. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60041. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60042. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60043. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60044. // Returns the GroundMesh.
  60045. GroundMesh.prototype._initHeightQuads = function () {
  60046. var subdivisionsX = this._subdivisionsX;
  60047. var subdivisionsY = this._subdivisionsY;
  60048. this._heightQuads = new Array();
  60049. for (var row = 0; row < subdivisionsY; row++) {
  60050. for (var col = 0; col < subdivisionsX; col++) {
  60051. 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) };
  60052. this._heightQuads[row * subdivisionsX + col] = quad;
  60053. }
  60054. }
  60055. return this;
  60056. };
  60057. // Compute each quad element values and update the the heightMap array :
  60058. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60059. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60060. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60061. // Returns the GroundMesh.
  60062. GroundMesh.prototype._computeHeightQuads = function () {
  60063. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60064. if (!positions) {
  60065. return this;
  60066. }
  60067. var v1 = BABYLON.Tmp.Vector3[3];
  60068. var v2 = BABYLON.Tmp.Vector3[2];
  60069. var v3 = BABYLON.Tmp.Vector3[1];
  60070. var v4 = BABYLON.Tmp.Vector3[0];
  60071. var v1v2 = BABYLON.Tmp.Vector3[4];
  60072. var v1v3 = BABYLON.Tmp.Vector3[5];
  60073. var v1v4 = BABYLON.Tmp.Vector3[6];
  60074. var norm1 = BABYLON.Tmp.Vector3[7];
  60075. var norm2 = BABYLON.Tmp.Vector3[8];
  60076. var i = 0;
  60077. var j = 0;
  60078. var k = 0;
  60079. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60080. var h = 0;
  60081. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60082. var d2 = 0;
  60083. var subdivisionsX = this._subdivisionsX;
  60084. var subdivisionsY = this._subdivisionsY;
  60085. for (var row = 0; row < subdivisionsY; row++) {
  60086. for (var col = 0; col < subdivisionsX; col++) {
  60087. i = col * 3;
  60088. j = row * (subdivisionsX + 1) * 3;
  60089. k = (row + 1) * (subdivisionsX + 1) * 3;
  60090. v1.x = positions[j + i];
  60091. v1.y = positions[j + i + 1];
  60092. v1.z = positions[j + i + 2];
  60093. v2.x = positions[j + i + 3];
  60094. v2.y = positions[j + i + 4];
  60095. v2.z = positions[j + i + 5];
  60096. v3.x = positions[k + i];
  60097. v3.y = positions[k + i + 1];
  60098. v3.z = positions[k + i + 2];
  60099. v4.x = positions[k + i + 3];
  60100. v4.y = positions[k + i + 4];
  60101. v4.z = positions[k + i + 5];
  60102. // 2D slope V1V4
  60103. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60104. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60105. // facet equations :
  60106. // we compute each facet normal vector
  60107. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60108. // we compute the value d by applying the equation to v1 which belongs to the plane
  60109. // then we store the facet equation in a Vector4
  60110. v2.subtractToRef(v1, v1v2);
  60111. v3.subtractToRef(v1, v1v3);
  60112. v4.subtractToRef(v1, v1v4);
  60113. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60114. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60115. norm1.normalize();
  60116. norm2.normalize();
  60117. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60118. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60119. var quad = this._heightQuads[row * subdivisionsX + col];
  60120. quad.slope.copyFromFloats(cd, h);
  60121. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60122. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60123. }
  60124. }
  60125. return this;
  60126. };
  60127. GroundMesh.prototype.serialize = function (serializationObject) {
  60128. _super.prototype.serialize.call(this, serializationObject);
  60129. serializationObject.subdivisionsX = this._subdivisionsX;
  60130. serializationObject.subdivisionsY = this._subdivisionsY;
  60131. serializationObject.minX = this._minX;
  60132. serializationObject.maxX = this._maxX;
  60133. serializationObject.minZ = this._minZ;
  60134. serializationObject.maxZ = this._maxZ;
  60135. serializationObject.width = this._width;
  60136. serializationObject.height = this._height;
  60137. };
  60138. GroundMesh.Parse = function (parsedMesh, scene) {
  60139. var result = new GroundMesh(parsedMesh.name, scene);
  60140. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60141. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60142. result._minX = parsedMesh.minX;
  60143. result._maxX = parsedMesh.maxX;
  60144. result._minZ = parsedMesh.minZ;
  60145. result._maxZ = parsedMesh.maxZ;
  60146. result._width = parsedMesh.width;
  60147. result._height = parsedMesh.height;
  60148. return result;
  60149. };
  60150. return GroundMesh;
  60151. }(BABYLON.Mesh));
  60152. BABYLON.GroundMesh = GroundMesh;
  60153. })(BABYLON || (BABYLON = {}));
  60154. //# sourceMappingURL=babylon.groundMesh.js.map
  60155. var BABYLON;
  60156. (function (BABYLON) {
  60157. /**
  60158. * Creates an instance based on a source mesh.
  60159. */
  60160. var InstancedMesh = /** @class */ (function (_super) {
  60161. __extends(InstancedMesh, _super);
  60162. function InstancedMesh(name, source) {
  60163. var _this = _super.call(this, name, source.getScene()) || this;
  60164. source.instances.push(_this);
  60165. _this._sourceMesh = source;
  60166. _this.position.copyFrom(source.position);
  60167. _this.rotation.copyFrom(source.rotation);
  60168. _this.scaling.copyFrom(source.scaling);
  60169. if (source.rotationQuaternion) {
  60170. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60171. }
  60172. _this.infiniteDistance = source.infiniteDistance;
  60173. _this.setPivotMatrix(source.getPivotMatrix());
  60174. _this.refreshBoundingInfo();
  60175. _this._syncSubMeshes();
  60176. return _this;
  60177. }
  60178. /**
  60179. * Returns the string "InstancedMesh".
  60180. */
  60181. InstancedMesh.prototype.getClassName = function () {
  60182. return "InstancedMesh";
  60183. };
  60184. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60185. // Methods
  60186. get: function () {
  60187. return this._sourceMesh.receiveShadows;
  60188. },
  60189. enumerable: true,
  60190. configurable: true
  60191. });
  60192. Object.defineProperty(InstancedMesh.prototype, "material", {
  60193. get: function () {
  60194. return this._sourceMesh.material;
  60195. },
  60196. enumerable: true,
  60197. configurable: true
  60198. });
  60199. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60200. get: function () {
  60201. return this._sourceMesh.visibility;
  60202. },
  60203. enumerable: true,
  60204. configurable: true
  60205. });
  60206. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60207. get: function () {
  60208. return this._sourceMesh.skeleton;
  60209. },
  60210. enumerable: true,
  60211. configurable: true
  60212. });
  60213. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60214. get: function () {
  60215. return this._sourceMesh.renderingGroupId;
  60216. },
  60217. set: function (value) {
  60218. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60219. return;
  60220. }
  60221. //no-op with warning
  60222. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60223. },
  60224. enumerable: true,
  60225. configurable: true
  60226. });
  60227. /**
  60228. * Returns the total number of vertices (integer).
  60229. */
  60230. InstancedMesh.prototype.getTotalVertices = function () {
  60231. return this._sourceMesh.getTotalVertices();
  60232. };
  60233. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60234. get: function () {
  60235. return this._sourceMesh;
  60236. },
  60237. enumerable: true,
  60238. configurable: true
  60239. });
  60240. /**
  60241. * Is this node ready to be used/rendered
  60242. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60243. * @return {boolean} is it ready
  60244. */
  60245. InstancedMesh.prototype.isReady = function (completeCheck) {
  60246. if (completeCheck === void 0) { completeCheck = false; }
  60247. return this._sourceMesh.isReady(completeCheck, true);
  60248. };
  60249. /**
  60250. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60251. */
  60252. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60253. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60254. };
  60255. /**
  60256. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60257. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60258. * The `data` are either a numeric array either a Float32Array.
  60259. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60260. * 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).
  60261. * Note that a new underlying VertexBuffer object is created each call.
  60262. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60263. *
  60264. * Possible `kind` values :
  60265. * - BABYLON.VertexBuffer.PositionKind
  60266. * - BABYLON.VertexBuffer.UVKind
  60267. * - BABYLON.VertexBuffer.UV2Kind
  60268. * - BABYLON.VertexBuffer.UV3Kind
  60269. * - BABYLON.VertexBuffer.UV4Kind
  60270. * - BABYLON.VertexBuffer.UV5Kind
  60271. * - BABYLON.VertexBuffer.UV6Kind
  60272. * - BABYLON.VertexBuffer.ColorKind
  60273. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60274. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60275. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60276. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60277. *
  60278. * Returns the Mesh.
  60279. */
  60280. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60281. if (this.sourceMesh) {
  60282. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60283. }
  60284. return this.sourceMesh;
  60285. };
  60286. /**
  60287. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60288. * If the mesh has no geometry, it is simply returned as it is.
  60289. * The `data` are either a numeric array either a Float32Array.
  60290. * No new underlying VertexBuffer object is created.
  60291. * 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.
  60292. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60293. *
  60294. * Possible `kind` values :
  60295. * - BABYLON.VertexBuffer.PositionKind
  60296. * - BABYLON.VertexBuffer.UVKind
  60297. * - BABYLON.VertexBuffer.UV2Kind
  60298. * - BABYLON.VertexBuffer.UV3Kind
  60299. * - BABYLON.VertexBuffer.UV4Kind
  60300. * - BABYLON.VertexBuffer.UV5Kind
  60301. * - BABYLON.VertexBuffer.UV6Kind
  60302. * - BABYLON.VertexBuffer.ColorKind
  60303. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60304. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60305. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60306. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60307. *
  60308. * Returns the Mesh.
  60309. */
  60310. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60311. if (this.sourceMesh) {
  60312. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60313. }
  60314. return this.sourceMesh;
  60315. };
  60316. /**
  60317. * Sets the mesh indices.
  60318. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60319. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60320. * This method creates a new index buffer each call.
  60321. * Returns the Mesh.
  60322. */
  60323. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60324. if (totalVertices === void 0) { totalVertices = null; }
  60325. if (this.sourceMesh) {
  60326. this.sourceMesh.setIndices(indices, totalVertices);
  60327. }
  60328. return this.sourceMesh;
  60329. };
  60330. /**
  60331. * Boolean : True if the mesh owns the requested kind of data.
  60332. */
  60333. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60334. return this._sourceMesh.isVerticesDataPresent(kind);
  60335. };
  60336. /**
  60337. * Returns an array of indices (IndicesArray).
  60338. */
  60339. InstancedMesh.prototype.getIndices = function () {
  60340. return this._sourceMesh.getIndices();
  60341. };
  60342. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60343. get: function () {
  60344. return this._sourceMesh._positions;
  60345. },
  60346. enumerable: true,
  60347. configurable: true
  60348. });
  60349. /**
  60350. * Sets a new updated BoundingInfo to the mesh.
  60351. * Returns the mesh.
  60352. */
  60353. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60354. var meshBB = this._sourceMesh.getBoundingInfo();
  60355. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60356. this._updateBoundingInfo();
  60357. return this;
  60358. };
  60359. InstancedMesh.prototype._preActivate = function () {
  60360. if (this._currentLOD) {
  60361. this._currentLOD._preActivate();
  60362. }
  60363. return this;
  60364. };
  60365. InstancedMesh.prototype._activate = function (renderId) {
  60366. if (this._currentLOD) {
  60367. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60368. }
  60369. return this;
  60370. };
  60371. /**
  60372. * Returns the current associated LOD AbstractMesh.
  60373. */
  60374. InstancedMesh.prototype.getLOD = function (camera) {
  60375. if (!camera) {
  60376. return this;
  60377. }
  60378. var boundingInfo = this.getBoundingInfo();
  60379. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60380. if (this._currentLOD === this.sourceMesh) {
  60381. return this;
  60382. }
  60383. return this._currentLOD;
  60384. };
  60385. InstancedMesh.prototype._syncSubMeshes = function () {
  60386. this.releaseSubMeshes();
  60387. if (this._sourceMesh.subMeshes) {
  60388. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60389. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60390. }
  60391. }
  60392. return this;
  60393. };
  60394. InstancedMesh.prototype._generatePointsArray = function () {
  60395. return this._sourceMesh._generatePointsArray();
  60396. };
  60397. /**
  60398. * Creates a new InstancedMesh from the current mesh.
  60399. * - name (string) : the cloned mesh name
  60400. * - newParent (optional Node) : the optional Node to parent the clone to.
  60401. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60402. *
  60403. * Returns the clone.
  60404. */
  60405. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60406. var result = this._sourceMesh.createInstance(name);
  60407. // Deep copy
  60408. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60409. // Bounding info
  60410. this.refreshBoundingInfo();
  60411. // Parent
  60412. if (newParent) {
  60413. result.parent = newParent;
  60414. }
  60415. if (!doNotCloneChildren) {
  60416. // Children
  60417. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60418. var mesh = this.getScene().meshes[index];
  60419. if (mesh.parent === this) {
  60420. mesh.clone(mesh.name, result);
  60421. }
  60422. }
  60423. }
  60424. result.computeWorldMatrix(true);
  60425. return result;
  60426. };
  60427. /**
  60428. * Disposes the InstancedMesh.
  60429. * Returns nothing.
  60430. */
  60431. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60432. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60433. // Remove from mesh
  60434. var index = this._sourceMesh.instances.indexOf(this);
  60435. this._sourceMesh.instances.splice(index, 1);
  60436. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60437. };
  60438. return InstancedMesh;
  60439. }(BABYLON.AbstractMesh));
  60440. BABYLON.InstancedMesh = InstancedMesh;
  60441. })(BABYLON || (BABYLON = {}));
  60442. //# sourceMappingURL=babylon.instancedMesh.js.map
  60443. var BABYLON;
  60444. (function (BABYLON) {
  60445. var LinesMesh = /** @class */ (function (_super) {
  60446. __extends(LinesMesh, _super);
  60447. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60448. if (scene === void 0) { scene = null; }
  60449. if (parent === void 0) { parent = null; }
  60450. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60451. _this.useVertexColor = useVertexColor;
  60452. _this.useVertexAlpha = useVertexAlpha;
  60453. _this.color = new BABYLON.Color3(1, 1, 1);
  60454. _this.alpha = 1;
  60455. if (source) {
  60456. _this.color = source.color.clone();
  60457. _this.alpha = source.alpha;
  60458. _this.useVertexColor = source.useVertexColor;
  60459. _this.useVertexAlpha = source.useVertexAlpha;
  60460. }
  60461. _this._intersectionThreshold = 0.1;
  60462. var defines = [];
  60463. var options = {
  60464. attributes: [BABYLON.VertexBuffer.PositionKind],
  60465. uniforms: ["world", "viewProjection"],
  60466. needAlphaBlending: true,
  60467. defines: defines
  60468. };
  60469. if (useVertexAlpha === false) {
  60470. options.needAlphaBlending = false;
  60471. }
  60472. if (!useVertexColor) {
  60473. options.uniforms.push("color");
  60474. }
  60475. else {
  60476. options.defines.push("#define VERTEXCOLOR");
  60477. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60478. }
  60479. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60480. return _this;
  60481. }
  60482. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60483. /**
  60484. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60485. * This margin is expressed in world space coordinates, so its value may vary.
  60486. * Default value is 0.1
  60487. * @returns the intersection Threshold value.
  60488. */
  60489. get: function () {
  60490. return this._intersectionThreshold;
  60491. },
  60492. /**
  60493. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60494. * This margin is expressed in world space coordinates, so its value may vary.
  60495. * @param value the new threshold to apply
  60496. */
  60497. set: function (value) {
  60498. if (this._intersectionThreshold === value) {
  60499. return;
  60500. }
  60501. this._intersectionThreshold = value;
  60502. if (this.geometry) {
  60503. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60504. }
  60505. },
  60506. enumerable: true,
  60507. configurable: true
  60508. });
  60509. /**
  60510. * Returns the string "LineMesh"
  60511. */
  60512. LinesMesh.prototype.getClassName = function () {
  60513. return "LinesMesh";
  60514. };
  60515. Object.defineProperty(LinesMesh.prototype, "material", {
  60516. get: function () {
  60517. return this._colorShader;
  60518. },
  60519. set: function (value) {
  60520. // Do nothing
  60521. },
  60522. enumerable: true,
  60523. configurable: true
  60524. });
  60525. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60526. get: function () {
  60527. return false;
  60528. },
  60529. enumerable: true,
  60530. configurable: true
  60531. });
  60532. LinesMesh.prototype.createInstance = function (name) {
  60533. throw new Error("LinesMeshes do not support createInstance.");
  60534. };
  60535. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60536. if (!this._geometry) {
  60537. return this;
  60538. }
  60539. // VBOs
  60540. this._geometry._bind(this._colorShader.getEffect());
  60541. // Color
  60542. if (!this.useVertexColor) {
  60543. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60544. }
  60545. return this;
  60546. };
  60547. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60548. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60549. return this;
  60550. }
  60551. var engine = this.getScene().getEngine();
  60552. // Draw order
  60553. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60554. return this;
  60555. };
  60556. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60557. this._colorShader.dispose();
  60558. _super.prototype.dispose.call(this, doNotRecurse);
  60559. };
  60560. /**
  60561. * Returns a new LineMesh object cloned from the current one.
  60562. */
  60563. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60564. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60565. };
  60566. return LinesMesh;
  60567. }(BABYLON.Mesh));
  60568. BABYLON.LinesMesh = LinesMesh;
  60569. })(BABYLON || (BABYLON = {}));
  60570. //# sourceMappingURL=babylon.linesMesh.js.map
  60571. var BABYLON;
  60572. (function (BABYLON) {
  60573. /**
  60574. * Class containing static functions to help procedurally build meshes
  60575. */
  60576. var MeshBuilder = /** @class */ (function () {
  60577. function MeshBuilder() {
  60578. }
  60579. MeshBuilder.updateSideOrientation = function (orientation) {
  60580. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60581. return BABYLON.Mesh.DOUBLESIDE;
  60582. }
  60583. if (orientation === undefined || orientation === null) {
  60584. return BABYLON.Mesh.FRONTSIDE;
  60585. }
  60586. return orientation;
  60587. };
  60588. /**
  60589. * Creates a box mesh
  60590. * * The parameter `size` sets the size (float) of each box side (default 1)
  60591. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60592. * * 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)
  60593. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60594. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60595. * * 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
  60596. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60597. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60598. * @param name defines the name of the mesh
  60599. * @param options defines the options used to create the mesh
  60600. * @param scene defines the hosting scene
  60601. * @returns the box mesh
  60602. */
  60603. MeshBuilder.CreateBox = function (name, options, scene) {
  60604. if (scene === void 0) { scene = null; }
  60605. var box = new BABYLON.Mesh(name, scene);
  60606. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60607. box._originalBuilderSideOrientation = options.sideOrientation;
  60608. var vertexData = BABYLON.VertexData.CreateBox(options);
  60609. vertexData.applyToMesh(box, options.updatable);
  60610. return box;
  60611. };
  60612. /**
  60613. * Creates a sphere mesh
  60614. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60615. * * 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`)
  60616. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60617. * * 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
  60618. * * 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)
  60619. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60620. * * 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
  60621. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60622. * @param name defines the name of the mesh
  60623. * @param options defines the options used to create the mesh
  60624. * @param scene defines the hosting scene
  60625. * @returns the sphere mesh
  60626. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60627. */
  60628. MeshBuilder.CreateSphere = function (name, options, scene) {
  60629. var sphere = new BABYLON.Mesh(name, scene);
  60630. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60631. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60632. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60633. vertexData.applyToMesh(sphere, options.updatable);
  60634. return sphere;
  60635. };
  60636. /**
  60637. * Creates a plane polygonal mesh. By default, this is a disc
  60638. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60639. * * 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
  60640. * * 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
  60641. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60642. * * 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
  60643. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60644. * @param name defines the name of the mesh
  60645. * @param options defines the options used to create the mesh
  60646. * @param scene defines the hosting scene
  60647. * @returns the plane polygonal mesh
  60648. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60649. */
  60650. MeshBuilder.CreateDisc = function (name, options, scene) {
  60651. if (scene === void 0) { scene = null; }
  60652. var disc = new BABYLON.Mesh(name, scene);
  60653. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60654. disc._originalBuilderSideOrientation = options.sideOrientation;
  60655. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60656. vertexData.applyToMesh(disc, options.updatable);
  60657. return disc;
  60658. };
  60659. /**
  60660. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60661. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60662. * * 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`)
  60663. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60664. * * 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
  60665. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60666. * * 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
  60667. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60668. * @param name defines the name of the mesh
  60669. * @param options defines the options used to create the mesh
  60670. * @param scene defines the hosting scene
  60671. * @returns the icosahedron mesh
  60672. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60673. */
  60674. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60675. var sphere = new BABYLON.Mesh(name, scene);
  60676. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60677. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60678. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60679. vertexData.applyToMesh(sphere, options.updatable);
  60680. return sphere;
  60681. };
  60682. ;
  60683. /**
  60684. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60685. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60686. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60687. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60688. * * 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
  60689. * * 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
  60690. * * 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
  60691. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60692. * * 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
  60693. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60694. * * 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
  60695. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60696. * * 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
  60697. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60698. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60699. * @param name defines the name of the mesh
  60700. * @param options defines the options used to create the mesh
  60701. * @param scene defines the hosting scene
  60702. * @returns the ribbon mesh
  60703. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60704. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60705. */
  60706. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60707. if (scene === void 0) { scene = null; }
  60708. var pathArray = options.pathArray;
  60709. var closeArray = options.closeArray;
  60710. var closePath = options.closePath;
  60711. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60712. var instance = options.instance;
  60713. var updatable = options.updatable;
  60714. if (instance) { // existing ribbon instance update
  60715. // positionFunction : ribbon case
  60716. // only pathArray and sideOrientation parameters are taken into account for positions update
  60717. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60718. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60719. var positionFunction = function (positions) {
  60720. var minlg = pathArray[0].length;
  60721. var i = 0;
  60722. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60723. for (var si = 1; si <= ns; si++) {
  60724. for (var p = 0; p < pathArray.length; p++) {
  60725. var path = pathArray[p];
  60726. var l = path.length;
  60727. minlg = (minlg < l) ? minlg : l;
  60728. var j = 0;
  60729. while (j < minlg) {
  60730. positions[i] = path[j].x;
  60731. positions[i + 1] = path[j].y;
  60732. positions[i + 2] = path[j].z;
  60733. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60734. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60735. }
  60736. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60737. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60738. }
  60739. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60740. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60741. }
  60742. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60743. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60744. }
  60745. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60746. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60747. }
  60748. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60749. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60750. }
  60751. j++;
  60752. i += 3;
  60753. }
  60754. if (instance._closePath) {
  60755. positions[i] = path[0].x;
  60756. positions[i + 1] = path[0].y;
  60757. positions[i + 2] = path[0].z;
  60758. i += 3;
  60759. }
  60760. }
  60761. }
  60762. };
  60763. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60764. positionFunction(positions);
  60765. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60766. instance._boundingInfo.update(instance._worldMatrix);
  60767. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60768. if (options.colors) {
  60769. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60770. for (var c = 0; c < options.colors.length; c++) {
  60771. colors[c * 4] = options.colors[c].r;
  60772. colors[c * 4 + 1] = options.colors[c].g;
  60773. colors[c * 4 + 2] = options.colors[c].b;
  60774. colors[c * 4 + 3] = options.colors[c].a;
  60775. }
  60776. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60777. }
  60778. if (options.uvs) {
  60779. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60780. for (var i = 0; i < options.uvs.length; i++) {
  60781. uvs[i * 2] = options.uvs[i].x;
  60782. uvs[i * 2 + 1] = options.uvs[i].y;
  60783. }
  60784. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60785. }
  60786. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60787. var indices = instance.getIndices();
  60788. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60789. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60790. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60791. if (instance._closePath) {
  60792. var indexFirst = 0;
  60793. var indexLast = 0;
  60794. for (var p = 0; p < pathArray.length; p++) {
  60795. indexFirst = instance._idx[p] * 3;
  60796. if (p + 1 < pathArray.length) {
  60797. indexLast = (instance._idx[p + 1] - 1) * 3;
  60798. }
  60799. else {
  60800. indexLast = normals.length - 3;
  60801. }
  60802. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60803. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60804. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60805. normals[indexLast] = normals[indexFirst];
  60806. normals[indexLast + 1] = normals[indexFirst + 1];
  60807. normals[indexLast + 2] = normals[indexFirst + 2];
  60808. }
  60809. }
  60810. if (!(instance.areNormalsFrozen)) {
  60811. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60812. }
  60813. }
  60814. return instance;
  60815. }
  60816. else { // new ribbon creation
  60817. var ribbon = new BABYLON.Mesh(name, scene);
  60818. ribbon._originalBuilderSideOrientation = sideOrientation;
  60819. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60820. if (closePath) {
  60821. ribbon._idx = vertexData._idx;
  60822. }
  60823. ribbon._closePath = closePath;
  60824. ribbon._closeArray = closeArray;
  60825. vertexData.applyToMesh(ribbon, updatable);
  60826. return ribbon;
  60827. }
  60828. };
  60829. /**
  60830. * Creates a cylinder or a cone mesh
  60831. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60832. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60833. * * 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.
  60834. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60835. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60836. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60837. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60838. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60839. * * 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).
  60840. * * 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
  60841. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60842. * * 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
  60843. * * 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.
  60844. * * If `enclose` is false, a ring surface is one element.
  60845. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60846. * * 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
  60847. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60848. * * 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
  60849. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60850. * @param name defines the name of the mesh
  60851. * @param options defines the options used to create the mesh
  60852. * @param scene defines the hosting scene
  60853. * @returns the cylinder mesh
  60854. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60855. */
  60856. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60857. var cylinder = new BABYLON.Mesh(name, scene);
  60858. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60859. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60860. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60861. vertexData.applyToMesh(cylinder, options.updatable);
  60862. return cylinder;
  60863. };
  60864. /**
  60865. * Creates a torus mesh
  60866. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60867. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60868. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60869. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60870. * * 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
  60871. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60872. * @param name defines the name of the mesh
  60873. * @param options defines the options used to create the mesh
  60874. * @param scene defines the hosting scene
  60875. * @returns the torus mesh
  60876. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60877. */
  60878. MeshBuilder.CreateTorus = function (name, options, scene) {
  60879. var torus = new BABYLON.Mesh(name, scene);
  60880. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60881. torus._originalBuilderSideOrientation = options.sideOrientation;
  60882. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60883. vertexData.applyToMesh(torus, options.updatable);
  60884. return torus;
  60885. };
  60886. /**
  60887. * Creates a torus knot mesh
  60888. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60889. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60890. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60891. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60892. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60893. * * 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
  60894. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60895. * @param name defines the name of the mesh
  60896. * @param options defines the options used to create the mesh
  60897. * @param scene defines the hosting scene
  60898. * @returns the torus knot mesh
  60899. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60900. */
  60901. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60902. var torusKnot = new BABYLON.Mesh(name, scene);
  60903. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60904. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60905. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60906. vertexData.applyToMesh(torusKnot, options.updatable);
  60907. return torusKnot;
  60908. };
  60909. /**
  60910. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60911. * * 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
  60912. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60913. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60914. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60915. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60916. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60917. * * 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
  60918. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60919. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60920. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60921. * @param name defines the name of the new line system
  60922. * @param options defines the options used to create the line system
  60923. * @param scene defines the hosting scene
  60924. * @returns a new line system mesh
  60925. */
  60926. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60927. var instance = options.instance;
  60928. var lines = options.lines;
  60929. var colors = options.colors;
  60930. if (instance) { // lines update
  60931. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60932. var vertexColor;
  60933. var lineColors;
  60934. if (colors) {
  60935. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60936. }
  60937. var i = 0;
  60938. var c = 0;
  60939. for (var l = 0; l < lines.length; l++) {
  60940. var points = lines[l];
  60941. for (var p = 0; p < points.length; p++) {
  60942. positions[i] = points[p].x;
  60943. positions[i + 1] = points[p].y;
  60944. positions[i + 2] = points[p].z;
  60945. if (colors && vertexColor) {
  60946. lineColors = colors[l];
  60947. vertexColor[c] = lineColors[p].r;
  60948. vertexColor[c + 1] = lineColors[p].g;
  60949. vertexColor[c + 2] = lineColors[p].b;
  60950. vertexColor[c + 3] = lineColors[p].a;
  60951. c += 4;
  60952. }
  60953. i += 3;
  60954. }
  60955. }
  60956. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60957. if (colors && vertexColor) {
  60958. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60959. }
  60960. return instance;
  60961. }
  60962. // line system creation
  60963. var useVertexColor = (colors) ? true : false;
  60964. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60965. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60966. vertexData.applyToMesh(lineSystem, options.updatable);
  60967. return lineSystem;
  60968. };
  60969. /**
  60970. * Creates a line mesh
  60971. * 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
  60972. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60973. * * The parameter `points` is an array successive Vector3
  60974. * * 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
  60975. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60976. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60977. * * When updating an instance, remember that only point positions can change, not the number of points
  60978. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60979. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60980. * @param name defines the name of the new line system
  60981. * @param options defines the options used to create the line system
  60982. * @param scene defines the hosting scene
  60983. * @returns a new line mesh
  60984. */
  60985. MeshBuilder.CreateLines = function (name, options, scene) {
  60986. if (scene === void 0) { scene = null; }
  60987. var colors = (options.colors) ? [options.colors] : null;
  60988. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60989. return lines;
  60990. };
  60991. /**
  60992. * Creates a dashed line mesh
  60993. * * 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
  60994. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60995. * * The parameter `points` is an array successive Vector3
  60996. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60997. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60998. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60999. * * 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
  61000. * * When updating an instance, remember that only point positions can change, not the number of points
  61001. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61002. * @param name defines the name of the mesh
  61003. * @param options defines the options used to create the mesh
  61004. * @param scene defines the hosting scene
  61005. * @returns the dashed line mesh
  61006. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61007. */
  61008. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61009. if (scene === void 0) { scene = null; }
  61010. var points = options.points;
  61011. var instance = options.instance;
  61012. var gapSize = options.gapSize || 1;
  61013. var dashSize = options.dashSize || 3;
  61014. if (instance) { // dashed lines update
  61015. var positionFunction = function (positions) {
  61016. var curvect = BABYLON.Vector3.Zero();
  61017. var nbSeg = positions.length / 6;
  61018. var lg = 0;
  61019. var nb = 0;
  61020. var shft = 0;
  61021. var dashshft = 0;
  61022. var curshft = 0;
  61023. var p = 0;
  61024. var i = 0;
  61025. var j = 0;
  61026. for (i = 0; i < points.length - 1; i++) {
  61027. points[i + 1].subtractToRef(points[i], curvect);
  61028. lg += curvect.length();
  61029. }
  61030. shft = lg / nbSeg;
  61031. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61032. for (i = 0; i < points.length - 1; i++) {
  61033. points[i + 1].subtractToRef(points[i], curvect);
  61034. nb = Math.floor(curvect.length() / shft);
  61035. curvect.normalize();
  61036. j = 0;
  61037. while (j < nb && p < positions.length) {
  61038. curshft = shft * j;
  61039. positions[p] = points[i].x + curshft * curvect.x;
  61040. positions[p + 1] = points[i].y + curshft * curvect.y;
  61041. positions[p + 2] = points[i].z + curshft * curvect.z;
  61042. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61043. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61044. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61045. p += 6;
  61046. j++;
  61047. }
  61048. }
  61049. while (p < positions.length) {
  61050. positions[p] = points[i].x;
  61051. positions[p + 1] = points[i].y;
  61052. positions[p + 2] = points[i].z;
  61053. p += 3;
  61054. }
  61055. };
  61056. instance.updateMeshPositions(positionFunction, false);
  61057. return instance;
  61058. }
  61059. // dashed lines creation
  61060. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61061. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61062. vertexData.applyToMesh(dashedLines, options.updatable);
  61063. dashedLines.dashSize = dashSize;
  61064. dashedLines.gapSize = gapSize;
  61065. return dashedLines;
  61066. };
  61067. /**
  61068. * 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.
  61069. * * 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.
  61070. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61071. * * 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.
  61072. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61073. * * 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
  61074. * * 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
  61075. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61076. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61077. * * 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
  61078. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61079. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61080. * @param name defines the name of the mesh
  61081. * @param options defines the options used to create the mesh
  61082. * @param scene defines the hosting scene
  61083. * @returns the extruded shape mesh
  61084. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61085. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61086. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61087. */
  61088. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61089. if (scene === void 0) { scene = null; }
  61090. var path = options.path;
  61091. var shape = options.shape;
  61092. var scale = options.scale || 1;
  61093. var rotation = options.rotation || 0;
  61094. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61095. var updatable = options.updatable;
  61096. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61097. var instance = options.instance || null;
  61098. var invertUV = options.invertUV || false;
  61099. 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);
  61100. };
  61101. /**
  61102. * Creates an custom extruded shape mesh.
  61103. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61104. * * 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.
  61105. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61106. * * 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
  61107. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61108. * * 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
  61109. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61110. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61111. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61112. * * 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
  61113. * * 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
  61114. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61115. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61116. * * 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
  61117. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61118. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61119. * @param name defines the name of the mesh
  61120. * @param options defines the options used to create the mesh
  61121. * @param scene defines the hosting scene
  61122. * @returns the custom extruded shape mesh
  61123. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61124. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61125. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61126. */
  61127. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61128. var path = options.path;
  61129. var shape = options.shape;
  61130. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61131. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61132. var ribbonCloseArray = options.ribbonCloseArray || false;
  61133. var ribbonClosePath = options.ribbonClosePath || false;
  61134. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61135. var updatable = options.updatable;
  61136. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61137. var instance = options.instance;
  61138. var invertUV = options.invertUV || false;
  61139. 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);
  61140. };
  61141. /**
  61142. * Creates lathe mesh.
  61143. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61144. * * 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
  61145. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61146. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61147. * * 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
  61148. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61149. * * 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
  61150. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61151. * * 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
  61152. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61153. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61154. * @param name defines the name of the mesh
  61155. * @param options defines the options used to create the mesh
  61156. * @param scene defines the hosting scene
  61157. * @returns the lathe mesh
  61158. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61159. */
  61160. MeshBuilder.CreateLathe = function (name, options, scene) {
  61161. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61162. var closed = (options.closed === undefined) ? true : options.closed;
  61163. var shape = options.shape;
  61164. var radius = options.radius || 1;
  61165. var tessellation = options.tessellation || 64;
  61166. var updatable = options.updatable;
  61167. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61168. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61169. var pi2 = Math.PI * 2;
  61170. var paths = new Array();
  61171. var invertUV = options.invertUV || false;
  61172. var i = 0;
  61173. var p = 0;
  61174. var step = pi2 / tessellation * arc;
  61175. var rotated;
  61176. var path = new Array();
  61177. for (i = 0; i <= tessellation; i++) {
  61178. var path = [];
  61179. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61180. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61181. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61182. }
  61183. for (p = 0; p < shape.length; p++) {
  61184. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61185. path.push(rotated);
  61186. }
  61187. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61188. 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));
  61189. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61190. }
  61191. paths.push(path);
  61192. }
  61193. // lathe ribbon
  61194. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61195. return lathe;
  61196. };
  61197. /**
  61198. * Creates a plane mesh
  61199. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61200. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61201. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61202. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61203. * * 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
  61204. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61205. * @param name defines the name of the mesh
  61206. * @param options defines the options used to create the mesh
  61207. * @param scene defines the hosting scene
  61208. * @returns the plane mesh
  61209. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61210. */
  61211. MeshBuilder.CreatePlane = function (name, options, scene) {
  61212. var plane = new BABYLON.Mesh(name, scene);
  61213. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61214. plane._originalBuilderSideOrientation = options.sideOrientation;
  61215. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61216. vertexData.applyToMesh(plane, options.updatable);
  61217. if (options.sourcePlane) {
  61218. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61219. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61220. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61221. plane.rotate(vectorProduct, product);
  61222. }
  61223. return plane;
  61224. };
  61225. /**
  61226. * Creates a ground mesh
  61227. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61228. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61229. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61230. * @param name defines the name of the mesh
  61231. * @param options defines the options used to create the mesh
  61232. * @param scene defines the hosting scene
  61233. * @returns the ground mesh
  61234. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61235. */
  61236. MeshBuilder.CreateGround = function (name, options, scene) {
  61237. var ground = new BABYLON.GroundMesh(name, scene);
  61238. ground._setReady(false);
  61239. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61240. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61241. ground._width = options.width || 1;
  61242. ground._height = options.height || 1;
  61243. ground._maxX = ground._width / 2;
  61244. ground._maxZ = ground._height / 2;
  61245. ground._minX = -ground._maxX;
  61246. ground._minZ = -ground._maxZ;
  61247. var vertexData = BABYLON.VertexData.CreateGround(options);
  61248. vertexData.applyToMesh(ground, options.updatable);
  61249. ground._setReady(true);
  61250. return ground;
  61251. };
  61252. /**
  61253. * Creates a tiled ground mesh
  61254. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61255. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61256. * * 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
  61257. * * 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
  61258. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61259. * @param name defines the name of the mesh
  61260. * @param options defines the options used to create the mesh
  61261. * @param scene defines the hosting scene
  61262. * @returns the tiled ground mesh
  61263. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61264. */
  61265. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61266. var tiledGround = new BABYLON.Mesh(name, scene);
  61267. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61268. vertexData.applyToMesh(tiledGround, options.updatable);
  61269. return tiledGround;
  61270. };
  61271. /**
  61272. * Creates a ground mesh from a height map
  61273. * * The parameter `url` sets the URL of the height map image resource.
  61274. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61275. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61276. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61277. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61278. * * 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.
  61279. * * 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).
  61280. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61281. * @param name defines the name of the mesh
  61282. * @param url defines the url to the height map
  61283. * @param options defines the options used to create the mesh
  61284. * @param scene defines the hosting scene
  61285. * @returns the ground mesh
  61286. * @see http://doc.babylonjs.com/babylon101/height_map
  61287. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61288. */
  61289. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61290. var width = options.width || 10.0;
  61291. var height = options.height || 10.0;
  61292. var subdivisions = options.subdivisions || 1 | 0;
  61293. var minHeight = options.minHeight || 0.0;
  61294. var maxHeight = options.maxHeight || 1.0;
  61295. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61296. var updatable = options.updatable;
  61297. var onReady = options.onReady;
  61298. var ground = new BABYLON.GroundMesh(name, scene);
  61299. ground._subdivisionsX = subdivisions;
  61300. ground._subdivisionsY = subdivisions;
  61301. ground._width = width;
  61302. ground._height = height;
  61303. ground._maxX = ground._width / 2.0;
  61304. ground._maxZ = ground._height / 2.0;
  61305. ground._minX = -ground._maxX;
  61306. ground._minZ = -ground._maxZ;
  61307. ground._setReady(false);
  61308. var onload = function (img) {
  61309. // Getting height map data
  61310. var canvas = document.createElement("canvas");
  61311. var context = canvas.getContext("2d");
  61312. if (!context) {
  61313. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61314. }
  61315. if (scene.isDisposed) {
  61316. return;
  61317. }
  61318. var bufferWidth = img.width;
  61319. var bufferHeight = img.height;
  61320. canvas.width = bufferWidth;
  61321. canvas.height = bufferHeight;
  61322. context.drawImage(img, 0, 0);
  61323. // Create VertexData from map data
  61324. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61325. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61326. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61327. width: width, height: height,
  61328. subdivisions: subdivisions,
  61329. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61330. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61331. });
  61332. vertexData.applyToMesh(ground, updatable);
  61333. //execute ready callback, if set
  61334. if (onReady) {
  61335. onReady(ground);
  61336. }
  61337. ground._setReady(true);
  61338. };
  61339. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61340. return ground;
  61341. };
  61342. /**
  61343. * Creates a polygon mesh
  61344. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61345. * * 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
  61346. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61347. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61348. * * 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)
  61349. * * Remember you can only change the shape positions, not their number when updating a polygon
  61350. * @param name defines the name of the mesh
  61351. * @param options defines the options used to create the mesh
  61352. * @param scene defines the hosting scene
  61353. * @returns the polygon mesh
  61354. */
  61355. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61356. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61357. var shape = options.shape;
  61358. var holes = options.holes || [];
  61359. var depth = options.depth || 0;
  61360. var contours = [];
  61361. var hole = [];
  61362. for (var i = 0; i < shape.length; i++) {
  61363. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61364. }
  61365. var epsilon = 0.00000001;
  61366. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61367. contours.pop();
  61368. }
  61369. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61370. for (var hNb = 0; hNb < holes.length; hNb++) {
  61371. hole = [];
  61372. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61373. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61374. }
  61375. polygonTriangulation.addHole(hole);
  61376. }
  61377. var polygon = polygonTriangulation.build(options.updatable, depth);
  61378. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61379. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61380. vertexData.applyToMesh(polygon, options.updatable);
  61381. return polygon;
  61382. };
  61383. ;
  61384. /**
  61385. * Creates an extruded polygon mesh, with depth in the Y direction.
  61386. * * 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)
  61387. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61388. * @param name defines the name of the mesh
  61389. * @param options defines the options used to create the mesh
  61390. * @param scene defines the hosting scene
  61391. * @returns the polygon mesh
  61392. */
  61393. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61394. return MeshBuilder.CreatePolygon(name, options, scene);
  61395. };
  61396. ;
  61397. /**
  61398. * Creates a tube mesh.
  61399. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61400. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61401. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61402. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61403. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61404. * * 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)
  61405. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61406. * * 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
  61407. * * 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
  61408. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61409. * * 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
  61410. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61411. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61412. * @param name defines the name of the mesh
  61413. * @param options defines the options used to create the mesh
  61414. * @param scene defines the hosting scene
  61415. * @returns the tube mesh
  61416. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61417. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61418. */
  61419. MeshBuilder.CreateTube = function (name, options, scene) {
  61420. var path = options.path;
  61421. var instance = options.instance;
  61422. var radius = 1.0;
  61423. if (instance) {
  61424. radius = instance.radius;
  61425. }
  61426. if (options.radius !== undefined) {
  61427. radius = options.radius;
  61428. }
  61429. ;
  61430. var tessellation = options.tessellation || 64 | 0;
  61431. var radiusFunction = options.radiusFunction || null;
  61432. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61433. var invertUV = options.invertUV || false;
  61434. var updatable = options.updatable;
  61435. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61436. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61437. // tube geometry
  61438. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61439. var tangents = path3D.getTangents();
  61440. var normals = path3D.getNormals();
  61441. var distances = path3D.getDistances();
  61442. var pi2 = Math.PI * 2;
  61443. var step = pi2 / tessellation * arc;
  61444. var returnRadius = function () { return radius; };
  61445. var radiusFunctionFinal = radiusFunction || returnRadius;
  61446. var circlePath;
  61447. var rad;
  61448. var normal;
  61449. var rotated;
  61450. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61451. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61452. for (var i = 0; i < path.length; i++) {
  61453. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61454. circlePath = Array(); // current circle array
  61455. normal = normals[i]; // current normal
  61456. for (var t = 0; t < tessellation; t++) {
  61457. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61458. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61459. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61460. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61461. circlePath[t] = rotated;
  61462. }
  61463. circlePaths[index] = circlePath;
  61464. index++;
  61465. }
  61466. // cap
  61467. var capPath = function (nbPoints, pathIndex) {
  61468. var pointCap = Array();
  61469. for (var i = 0; i < nbPoints; i++) {
  61470. pointCap.push(path[pathIndex]);
  61471. }
  61472. return pointCap;
  61473. };
  61474. switch (cap) {
  61475. case BABYLON.Mesh.NO_CAP:
  61476. break;
  61477. case BABYLON.Mesh.CAP_START:
  61478. circlePaths[0] = capPath(tessellation, 0);
  61479. circlePaths[1] = circlePaths[2].slice(0);
  61480. break;
  61481. case BABYLON.Mesh.CAP_END:
  61482. circlePaths[index] = circlePaths[index - 1].slice(0);
  61483. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61484. break;
  61485. case BABYLON.Mesh.CAP_ALL:
  61486. circlePaths[0] = capPath(tessellation, 0);
  61487. circlePaths[1] = circlePaths[2].slice(0);
  61488. circlePaths[index] = circlePaths[index - 1].slice(0);
  61489. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61490. break;
  61491. default:
  61492. break;
  61493. }
  61494. return circlePaths;
  61495. };
  61496. var path3D;
  61497. var pathArray;
  61498. if (instance) { // tube update
  61499. var arc = options.arc || instance.arc;
  61500. path3D = (instance.path3D).update(path);
  61501. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61502. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61503. instance.path3D = path3D;
  61504. instance.pathArray = pathArray;
  61505. instance.arc = arc;
  61506. instance.radius = radius;
  61507. return instance;
  61508. }
  61509. // tube creation
  61510. path3D = new BABYLON.Path3D(path);
  61511. var newPathArray = new Array();
  61512. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61513. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61514. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61515. tube.pathArray = pathArray;
  61516. tube.path3D = path3D;
  61517. tube.tessellation = tessellation;
  61518. tube.cap = cap;
  61519. tube.arc = options.arc;
  61520. tube.radius = radius;
  61521. return tube;
  61522. };
  61523. /**
  61524. * Creates a polyhedron mesh
  61525. * * 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
  61526. * * The parameter `size` (positive float, default 1) sets the polygon size
  61527. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61528. * * 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`
  61529. * * 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
  61530. * * 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)`)
  61531. * * 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
  61532. * * 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
  61533. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61534. * * 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
  61535. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61536. * @param name defines the name of the mesh
  61537. * @param options defines the options used to create the mesh
  61538. * @param scene defines the hosting scene
  61539. * @returns the polyhedron mesh
  61540. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61541. */
  61542. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61543. var polyhedron = new BABYLON.Mesh(name, scene);
  61544. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61545. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61546. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61547. vertexData.applyToMesh(polyhedron, options.updatable);
  61548. return polyhedron;
  61549. };
  61550. /**
  61551. * Creates a decal mesh.
  61552. * 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
  61553. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61554. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61555. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61556. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61557. * @param name defines the name of the mesh
  61558. * @param sourceMesh defines the mesh where the decal must be applied
  61559. * @param options defines the options used to create the mesh
  61560. * @param scene defines the hosting scene
  61561. * @returns the decal mesh
  61562. * @see http://doc.babylonjs.com/how_to/decals
  61563. */
  61564. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61565. var indices = sourceMesh.getIndices();
  61566. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61567. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61568. var position = options.position || BABYLON.Vector3.Zero();
  61569. var normal = options.normal || BABYLON.Vector3.Up();
  61570. var size = options.size || BABYLON.Vector3.One();
  61571. var angle = options.angle || 0;
  61572. // Getting correct rotation
  61573. if (!normal) {
  61574. var target = new BABYLON.Vector3(0, 0, 1);
  61575. var camera = sourceMesh.getScene().activeCamera;
  61576. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61577. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61578. }
  61579. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61580. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61581. var pitch = Math.atan2(normal.y, len);
  61582. // Matrix
  61583. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61584. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61585. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61586. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61587. var vertexData = new BABYLON.VertexData();
  61588. vertexData.indices = [];
  61589. vertexData.positions = [];
  61590. vertexData.normals = [];
  61591. vertexData.uvs = [];
  61592. var currentVertexDataIndex = 0;
  61593. var extractDecalVector3 = function (indexId) {
  61594. var result = new BABYLON.PositionNormalVertex();
  61595. if (!indices || !positions || !normals) {
  61596. return result;
  61597. }
  61598. var vertexId = indices[indexId];
  61599. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61600. // Send vector to decal local world
  61601. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61602. // Get normal
  61603. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61604. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61605. return result;
  61606. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61607. var clip = function (vertices, axis) {
  61608. if (vertices.length === 0) {
  61609. return vertices;
  61610. }
  61611. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61612. var clipVertices = function (v0, v1) {
  61613. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61614. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61615. };
  61616. var result = new Array();
  61617. for (var index = 0; index < vertices.length; index += 3) {
  61618. var v1Out;
  61619. var v2Out;
  61620. var v3Out;
  61621. var total = 0;
  61622. var nV1 = null;
  61623. var nV2 = null;
  61624. var nV3 = null;
  61625. var nV4 = null;
  61626. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61627. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61628. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61629. v1Out = d1 > 0;
  61630. v2Out = d2 > 0;
  61631. v3Out = d3 > 0;
  61632. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61633. switch (total) {
  61634. case 0:
  61635. result.push(vertices[index]);
  61636. result.push(vertices[index + 1]);
  61637. result.push(vertices[index + 2]);
  61638. break;
  61639. case 1:
  61640. if (v1Out) {
  61641. nV1 = vertices[index + 1];
  61642. nV2 = vertices[index + 2];
  61643. nV3 = clipVertices(vertices[index], nV1);
  61644. nV4 = clipVertices(vertices[index], nV2);
  61645. }
  61646. if (v2Out) {
  61647. nV1 = vertices[index];
  61648. nV2 = vertices[index + 2];
  61649. nV3 = clipVertices(vertices[index + 1], nV1);
  61650. nV4 = clipVertices(vertices[index + 1], nV2);
  61651. result.push(nV3);
  61652. result.push(nV2.clone());
  61653. result.push(nV1.clone());
  61654. result.push(nV2.clone());
  61655. result.push(nV3.clone());
  61656. result.push(nV4);
  61657. break;
  61658. }
  61659. if (v3Out) {
  61660. nV1 = vertices[index];
  61661. nV2 = vertices[index + 1];
  61662. nV3 = clipVertices(vertices[index + 2], nV1);
  61663. nV4 = clipVertices(vertices[index + 2], nV2);
  61664. }
  61665. if (nV1 && nV2 && nV3 && nV4) {
  61666. result.push(nV1.clone());
  61667. result.push(nV2.clone());
  61668. result.push(nV3);
  61669. result.push(nV4);
  61670. result.push(nV3.clone());
  61671. result.push(nV2.clone());
  61672. }
  61673. break;
  61674. case 2:
  61675. if (!v1Out) {
  61676. nV1 = vertices[index].clone();
  61677. nV2 = clipVertices(nV1, vertices[index + 1]);
  61678. nV3 = clipVertices(nV1, vertices[index + 2]);
  61679. result.push(nV1);
  61680. result.push(nV2);
  61681. result.push(nV3);
  61682. }
  61683. if (!v2Out) {
  61684. nV1 = vertices[index + 1].clone();
  61685. nV2 = clipVertices(nV1, vertices[index + 2]);
  61686. nV3 = clipVertices(nV1, vertices[index]);
  61687. result.push(nV1);
  61688. result.push(nV2);
  61689. result.push(nV3);
  61690. }
  61691. if (!v3Out) {
  61692. nV1 = vertices[index + 2].clone();
  61693. nV2 = clipVertices(nV1, vertices[index]);
  61694. nV3 = clipVertices(nV1, vertices[index + 1]);
  61695. result.push(nV1);
  61696. result.push(nV2);
  61697. result.push(nV3);
  61698. }
  61699. break;
  61700. case 3:
  61701. break;
  61702. }
  61703. }
  61704. return result;
  61705. };
  61706. for (var index = 0; index < indices.length; index += 3) {
  61707. var faceVertices = new Array();
  61708. faceVertices.push(extractDecalVector3(index));
  61709. faceVertices.push(extractDecalVector3(index + 1));
  61710. faceVertices.push(extractDecalVector3(index + 2));
  61711. // Clip
  61712. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61713. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61714. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61715. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61716. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61717. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61718. if (faceVertices.length === 0) {
  61719. continue;
  61720. }
  61721. // Add UVs and get back to world
  61722. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61723. var vertex = faceVertices[vIndex];
  61724. //TODO check for Int32Array | Uint32Array | Uint16Array
  61725. vertexData.indices.push(currentVertexDataIndex);
  61726. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61727. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61728. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61729. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61730. currentVertexDataIndex++;
  61731. }
  61732. }
  61733. // Return mesh
  61734. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61735. vertexData.applyToMesh(decal);
  61736. decal.position = position.clone();
  61737. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61738. return decal;
  61739. };
  61740. // Privates
  61741. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61742. // extrusion geometry
  61743. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61744. var tangents = path3D.getTangents();
  61745. var normals = path3D.getNormals();
  61746. var binormals = path3D.getBinormals();
  61747. var distances = path3D.getDistances();
  61748. var angle = 0;
  61749. var returnScale = function () { return scale !== null ? scale : 1; };
  61750. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61751. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61752. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61753. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61754. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61755. for (var i = 0; i < curve.length; i++) {
  61756. var shapePath = new Array();
  61757. var angleStep = rotate(i, distances[i]);
  61758. var scaleRatio = scl(i, distances[i]);
  61759. for (var p = 0; p < shape.length; p++) {
  61760. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61761. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61762. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61763. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61764. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61765. shapePath[p] = rotated;
  61766. }
  61767. shapePaths[index] = shapePath;
  61768. angle += angleStep;
  61769. index++;
  61770. }
  61771. // cap
  61772. var capPath = function (shapePath) {
  61773. var pointCap = Array();
  61774. var barycenter = BABYLON.Vector3.Zero();
  61775. var i;
  61776. for (i = 0; i < shapePath.length; i++) {
  61777. barycenter.addInPlace(shapePath[i]);
  61778. }
  61779. barycenter.scaleInPlace(1.0 / shapePath.length);
  61780. for (i = 0; i < shapePath.length; i++) {
  61781. pointCap.push(barycenter);
  61782. }
  61783. return pointCap;
  61784. };
  61785. switch (cap) {
  61786. case BABYLON.Mesh.NO_CAP:
  61787. break;
  61788. case BABYLON.Mesh.CAP_START:
  61789. shapePaths[0] = capPath(shapePaths[2]);
  61790. shapePaths[1] = shapePaths[2];
  61791. break;
  61792. case BABYLON.Mesh.CAP_END:
  61793. shapePaths[index] = shapePaths[index - 1];
  61794. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61795. break;
  61796. case BABYLON.Mesh.CAP_ALL:
  61797. shapePaths[0] = capPath(shapePaths[2]);
  61798. shapePaths[1] = shapePaths[2];
  61799. shapePaths[index] = shapePaths[index - 1];
  61800. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61801. break;
  61802. default:
  61803. break;
  61804. }
  61805. return shapePaths;
  61806. };
  61807. var path3D;
  61808. var pathArray;
  61809. if (instance) { // instance update
  61810. path3D = (instance.path3D).update(curve);
  61811. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61812. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61813. return instance;
  61814. }
  61815. // extruded shape creation
  61816. path3D = new BABYLON.Path3D(curve);
  61817. var newShapePaths = new Array();
  61818. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61819. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61820. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61821. extrudedGeneric.pathArray = pathArray;
  61822. extrudedGeneric.path3D = path3D;
  61823. extrudedGeneric.cap = cap;
  61824. return extrudedGeneric;
  61825. };
  61826. return MeshBuilder;
  61827. }());
  61828. BABYLON.MeshBuilder = MeshBuilder;
  61829. })(BABYLON || (BABYLON = {}));
  61830. //# sourceMappingURL=babylon.meshBuilder.js.map
  61831. var BABYLON;
  61832. (function (BABYLON) {
  61833. /**
  61834. * Draco compression (https://google.github.io/draco/)
  61835. */
  61836. var DracoCompression = /** @class */ (function () {
  61837. /**
  61838. * Constructor
  61839. */
  61840. function DracoCompression() {
  61841. }
  61842. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61843. /**
  61844. * Returns true if the decoder is available.
  61845. */
  61846. get: function () {
  61847. if (typeof DracoDecoderModule !== "undefined") {
  61848. return true;
  61849. }
  61850. var decoder = DracoCompression.Configuration.decoder;
  61851. if (decoder) {
  61852. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61853. return true;
  61854. }
  61855. if (decoder.fallbackUrl) {
  61856. return true;
  61857. }
  61858. }
  61859. return false;
  61860. },
  61861. enumerable: true,
  61862. configurable: true
  61863. });
  61864. /**
  61865. * Stop all async operations and release resources.
  61866. */
  61867. DracoCompression.prototype.dispose = function () {
  61868. };
  61869. /**
  61870. * Decode Draco compressed mesh data to vertex data.
  61871. * @param data The array buffer view for the Draco compression data
  61872. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61873. * @returns A promise that resolves with the decoded vertex data
  61874. */
  61875. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61876. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61877. var module = wrappedModule.module;
  61878. var vertexData = new BABYLON.VertexData();
  61879. var buffer = new module.DecoderBuffer();
  61880. buffer.Init(data, data.byteLength);
  61881. var decoder = new module.Decoder();
  61882. var geometry;
  61883. var status;
  61884. try {
  61885. var type = decoder.GetEncodedGeometryType(buffer);
  61886. switch (type) {
  61887. case module.TRIANGULAR_MESH:
  61888. geometry = new module.Mesh();
  61889. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61890. break;
  61891. case module.POINT_CLOUD:
  61892. geometry = new module.PointCloud();
  61893. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61894. break;
  61895. default:
  61896. throw new Error("Invalid geometry type " + type);
  61897. }
  61898. if (!status.ok() || !geometry.ptr) {
  61899. throw new Error(status.error_msg());
  61900. }
  61901. var numPoints = geometry.num_points();
  61902. if (type === module.TRIANGULAR_MESH) {
  61903. var numFaces = geometry.num_faces();
  61904. var faceIndices = new module.DracoInt32Array();
  61905. try {
  61906. var indices = new Uint32Array(numFaces * 3);
  61907. for (var i = 0; i < numFaces; i++) {
  61908. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61909. var offset = i * 3;
  61910. indices[offset + 0] = faceIndices.GetValue(0);
  61911. indices[offset + 1] = faceIndices.GetValue(1);
  61912. indices[offset + 2] = faceIndices.GetValue(2);
  61913. }
  61914. vertexData.indices = indices;
  61915. }
  61916. finally {
  61917. module.destroy(faceIndices);
  61918. }
  61919. }
  61920. for (var kind in attributes) {
  61921. var uniqueId = attributes[kind];
  61922. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61923. var dracoData = new module.DracoFloat32Array();
  61924. try {
  61925. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61926. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61927. for (var i = 0; i < babylonData.length; i++) {
  61928. babylonData[i] = dracoData.GetValue(i);
  61929. }
  61930. vertexData.set(babylonData, kind);
  61931. }
  61932. finally {
  61933. module.destroy(dracoData);
  61934. }
  61935. }
  61936. }
  61937. finally {
  61938. if (geometry) {
  61939. module.destroy(geometry);
  61940. }
  61941. module.destroy(decoder);
  61942. module.destroy(buffer);
  61943. }
  61944. return vertexData;
  61945. });
  61946. };
  61947. DracoCompression._GetDecoderModule = function () {
  61948. if (!DracoCompression._DecoderModulePromise) {
  61949. var promise = null;
  61950. var config_1 = {};
  61951. if (typeof DracoDecoderModule !== "undefined") {
  61952. promise = Promise.resolve();
  61953. }
  61954. else {
  61955. var decoder = DracoCompression.Configuration.decoder;
  61956. if (decoder) {
  61957. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61958. promise = Promise.all([
  61959. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61960. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61961. config_1.wasmBinary = data;
  61962. })
  61963. ]);
  61964. }
  61965. else if (decoder.fallbackUrl) {
  61966. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61967. }
  61968. }
  61969. }
  61970. if (!promise) {
  61971. throw new Error("Draco decoder module is not available");
  61972. }
  61973. DracoCompression._DecoderModulePromise = promise.then(function () {
  61974. return new Promise(function (resolve) {
  61975. config_1.onModuleLoaded = function (decoderModule) {
  61976. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61977. resolve({ module: decoderModule });
  61978. };
  61979. DracoDecoderModule(config_1);
  61980. });
  61981. });
  61982. }
  61983. return DracoCompression._DecoderModulePromise;
  61984. };
  61985. DracoCompression._LoadScriptAsync = function (url) {
  61986. return new Promise(function (resolve, reject) {
  61987. BABYLON.Tools.LoadScript(url, function () {
  61988. resolve();
  61989. }, function (message) {
  61990. reject(new Error(message));
  61991. });
  61992. });
  61993. };
  61994. DracoCompression._LoadFileAsync = function (url) {
  61995. return new Promise(function (resolve, reject) {
  61996. BABYLON.Tools.LoadFile(url, function (data) {
  61997. resolve(data);
  61998. }, undefined, undefined, true, function (request, exception) {
  61999. reject(exception);
  62000. });
  62001. });
  62002. };
  62003. /**
  62004. * The configuration.
  62005. */
  62006. DracoCompression.Configuration = {
  62007. decoder: {
  62008. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62009. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62010. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62011. }
  62012. };
  62013. return DracoCompression;
  62014. }());
  62015. BABYLON.DracoCompression = DracoCompression;
  62016. })(BABYLON || (BABYLON = {}));
  62017. //# sourceMappingURL=babylon.dracoCompression.js.map
  62018. var BABYLON;
  62019. (function (BABYLON) {
  62020. var AudioEngine = /** @class */ (function () {
  62021. function AudioEngine() {
  62022. this._audioContext = null;
  62023. this._audioContextInitialized = false;
  62024. this.canUseWebAudio = false;
  62025. this.WarnedWebAudioUnsupported = false;
  62026. this.unlocked = false;
  62027. this.isMP3supported = false;
  62028. this.isOGGsupported = false;
  62029. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62030. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62031. this.canUseWebAudio = true;
  62032. }
  62033. var audioElem = document.createElement('audio');
  62034. try {
  62035. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62036. this.isMP3supported = true;
  62037. }
  62038. }
  62039. catch (e) {
  62040. // protect error during capability check.
  62041. }
  62042. try {
  62043. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62044. this.isOGGsupported = true;
  62045. }
  62046. }
  62047. catch (e) {
  62048. // protect error during capability check.
  62049. }
  62050. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62051. this._unlockiOSaudio();
  62052. }
  62053. else {
  62054. this.unlocked = true;
  62055. }
  62056. }
  62057. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62058. get: function () {
  62059. if (!this._audioContextInitialized) {
  62060. this._initializeAudioContext();
  62061. }
  62062. return this._audioContext;
  62063. },
  62064. enumerable: true,
  62065. configurable: true
  62066. });
  62067. AudioEngine.prototype._unlockiOSaudio = function () {
  62068. var _this = this;
  62069. var unlockaudio = function () {
  62070. if (!_this.audioContext) {
  62071. return;
  62072. }
  62073. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62074. var source = _this.audioContext.createBufferSource();
  62075. source.buffer = buffer;
  62076. source.connect(_this.audioContext.destination);
  62077. source.start(0);
  62078. setTimeout(function () {
  62079. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62080. _this.unlocked = true;
  62081. window.removeEventListener('touchend', unlockaudio, false);
  62082. if (_this.onAudioUnlocked) {
  62083. _this.onAudioUnlocked();
  62084. }
  62085. }
  62086. }, 0);
  62087. };
  62088. window.addEventListener('touchend', unlockaudio, false);
  62089. };
  62090. AudioEngine.prototype._initializeAudioContext = function () {
  62091. try {
  62092. if (this.canUseWebAudio) {
  62093. this._audioContext = new AudioContext();
  62094. // create a global volume gain node
  62095. this.masterGain = this._audioContext.createGain();
  62096. this.masterGain.gain.value = 1;
  62097. this.masterGain.connect(this._audioContext.destination);
  62098. this._audioContextInitialized = true;
  62099. }
  62100. }
  62101. catch (e) {
  62102. this.canUseWebAudio = false;
  62103. BABYLON.Tools.Error("Web Audio: " + e.message);
  62104. }
  62105. };
  62106. AudioEngine.prototype.dispose = function () {
  62107. if (this.canUseWebAudio && this._audioContextInitialized) {
  62108. if (this._connectedAnalyser && this._audioContext) {
  62109. this._connectedAnalyser.stopDebugCanvas();
  62110. this._connectedAnalyser.dispose();
  62111. this.masterGain.disconnect();
  62112. this.masterGain.connect(this._audioContext.destination);
  62113. this._connectedAnalyser = null;
  62114. }
  62115. this.masterGain.gain.value = 1;
  62116. }
  62117. this.WarnedWebAudioUnsupported = false;
  62118. };
  62119. AudioEngine.prototype.getGlobalVolume = function () {
  62120. if (this.canUseWebAudio && this._audioContextInitialized) {
  62121. return this.masterGain.gain.value;
  62122. }
  62123. else {
  62124. return -1;
  62125. }
  62126. };
  62127. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62128. if (this.canUseWebAudio && this._audioContextInitialized) {
  62129. this.masterGain.gain.value = newVolume;
  62130. }
  62131. };
  62132. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62133. if (this._connectedAnalyser) {
  62134. this._connectedAnalyser.stopDebugCanvas();
  62135. }
  62136. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62137. this._connectedAnalyser = analyser;
  62138. this.masterGain.disconnect();
  62139. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62140. }
  62141. };
  62142. return AudioEngine;
  62143. }());
  62144. BABYLON.AudioEngine = AudioEngine;
  62145. })(BABYLON || (BABYLON = {}));
  62146. //# sourceMappingURL=babylon.audioEngine.js.map
  62147. var BABYLON;
  62148. (function (BABYLON) {
  62149. var Sound = /** @class */ (function () {
  62150. /**
  62151. * Create a sound and attach it to a scene
  62152. * @param name Name of your sound
  62153. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62154. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62155. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62156. */
  62157. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62158. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62159. var _this = this;
  62160. this.autoplay = false;
  62161. this.loop = false;
  62162. this.useCustomAttenuation = false;
  62163. this.spatialSound = false;
  62164. this.refDistance = 1;
  62165. this.rolloffFactor = 1;
  62166. this.maxDistance = 100;
  62167. this.distanceModel = "linear";
  62168. this._panningModel = "equalpower";
  62169. this._playbackRate = 1;
  62170. this._streaming = false;
  62171. this._startTime = 0;
  62172. this._startOffset = 0;
  62173. this._position = BABYLON.Vector3.Zero();
  62174. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62175. this._volume = 1;
  62176. this._isReadyToPlay = false;
  62177. this.isPlaying = false;
  62178. this.isPaused = false;
  62179. this._isDirectional = false;
  62180. // Used if you'd like to create a directional sound.
  62181. // If not set, the sound will be omnidirectional
  62182. this._coneInnerAngle = 360;
  62183. this._coneOuterAngle = 360;
  62184. this._coneOuterGain = 0;
  62185. this._isOutputConnected = false;
  62186. this._urlType = "Unknown";
  62187. this.name = name;
  62188. this._scene = scene;
  62189. this._readyToPlayCallback = readyToPlayCallback;
  62190. // Default custom attenuation function is a linear attenuation
  62191. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62192. if (currentDistance < maxDistance) {
  62193. return currentVolume * (1 - currentDistance / maxDistance);
  62194. }
  62195. else {
  62196. return 0;
  62197. }
  62198. };
  62199. if (options) {
  62200. this.autoplay = options.autoplay || false;
  62201. this.loop = options.loop || false;
  62202. // if volume === 0, we need another way to check this option
  62203. if (options.volume !== undefined) {
  62204. this._volume = options.volume;
  62205. }
  62206. this.spatialSound = options.spatialSound || false;
  62207. this.maxDistance = options.maxDistance || 100;
  62208. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62209. this.rolloffFactor = options.rolloffFactor || 1;
  62210. this.refDistance = options.refDistance || 1;
  62211. this.distanceModel = options.distanceModel || "linear";
  62212. this._playbackRate = options.playbackRate || 1;
  62213. this._streaming = options.streaming || false;
  62214. }
  62215. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62216. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62217. this._soundGain.gain.value = this._volume;
  62218. this._inputAudioNode = this._soundGain;
  62219. this._ouputAudioNode = this._soundGain;
  62220. if (this.spatialSound) {
  62221. this._createSpatialParameters();
  62222. }
  62223. this._scene.mainSoundTrack.AddSound(this);
  62224. var validParameter = true;
  62225. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62226. if (urlOrArrayBuffer) {
  62227. try {
  62228. if (typeof (urlOrArrayBuffer) === "string")
  62229. this._urlType = "String";
  62230. if (Array.isArray(urlOrArrayBuffer))
  62231. this._urlType = "Array";
  62232. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62233. this._urlType = "ArrayBuffer";
  62234. var urls = [];
  62235. var codecSupportedFound = false;
  62236. switch (this._urlType) {
  62237. case "ArrayBuffer":
  62238. if (urlOrArrayBuffer.byteLength > 0) {
  62239. codecSupportedFound = true;
  62240. this._soundLoaded(urlOrArrayBuffer);
  62241. }
  62242. break;
  62243. case "String":
  62244. urls.push(urlOrArrayBuffer);
  62245. case "Array":
  62246. if (urls.length === 0)
  62247. urls = urlOrArrayBuffer;
  62248. // If we found a supported format, we load it immediately and stop the loop
  62249. for (var i = 0; i < urls.length; i++) {
  62250. var url = urls[i];
  62251. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62252. codecSupportedFound = true;
  62253. }
  62254. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62255. codecSupportedFound = true;
  62256. }
  62257. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62258. codecSupportedFound = true;
  62259. }
  62260. if (url.indexOf("blob:") !== -1) {
  62261. codecSupportedFound = true;
  62262. }
  62263. if (codecSupportedFound) {
  62264. // Loading sound using XHR2
  62265. if (!this._streaming) {
  62266. this._scene._loadFile(url, function (data) {
  62267. _this._soundLoaded(data);
  62268. }, undefined, true, true, function (exception) {
  62269. if (exception) {
  62270. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62271. }
  62272. BABYLON.Tools.Error("Sound creation aborted.");
  62273. _this._scene.mainSoundTrack.RemoveSound(_this);
  62274. });
  62275. }
  62276. // Streaming sound using HTML5 Audio tag
  62277. else {
  62278. this._htmlAudioElement = new Audio(url);
  62279. this._htmlAudioElement.controls = false;
  62280. this._htmlAudioElement.loop = this.loop;
  62281. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62282. this._htmlAudioElement.preload = "auto";
  62283. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62284. _this._isReadyToPlay = true;
  62285. if (_this.autoplay) {
  62286. _this.play();
  62287. }
  62288. if (_this._readyToPlayCallback) {
  62289. _this._readyToPlayCallback();
  62290. }
  62291. });
  62292. document.body.appendChild(this._htmlAudioElement);
  62293. }
  62294. break;
  62295. }
  62296. }
  62297. break;
  62298. default:
  62299. validParameter = false;
  62300. break;
  62301. }
  62302. if (!validParameter) {
  62303. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62304. }
  62305. else {
  62306. if (!codecSupportedFound) {
  62307. this._isReadyToPlay = true;
  62308. // Simulating a ready to play event to avoid breaking code path
  62309. if (this._readyToPlayCallback) {
  62310. window.setTimeout(function () {
  62311. if (_this._readyToPlayCallback) {
  62312. _this._readyToPlayCallback();
  62313. }
  62314. }, 1000);
  62315. }
  62316. }
  62317. }
  62318. }
  62319. catch (ex) {
  62320. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62321. this._scene.mainSoundTrack.RemoveSound(this);
  62322. }
  62323. }
  62324. }
  62325. else {
  62326. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62327. this._scene.mainSoundTrack.AddSound(this);
  62328. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62329. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62330. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62331. }
  62332. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62333. if (this._readyToPlayCallback) {
  62334. window.setTimeout(function () {
  62335. if (_this._readyToPlayCallback) {
  62336. _this._readyToPlayCallback();
  62337. }
  62338. }, 1000);
  62339. }
  62340. }
  62341. }
  62342. Sound.prototype.dispose = function () {
  62343. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62344. if (this.isPlaying) {
  62345. this.stop();
  62346. }
  62347. this._isReadyToPlay = false;
  62348. if (this.soundTrackId === -1) {
  62349. this._scene.mainSoundTrack.RemoveSound(this);
  62350. }
  62351. else {
  62352. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62353. }
  62354. if (this._soundGain) {
  62355. this._soundGain.disconnect();
  62356. this._soundGain = null;
  62357. }
  62358. if (this._soundPanner) {
  62359. this._soundPanner.disconnect();
  62360. this._soundPanner = null;
  62361. }
  62362. if (this._soundSource) {
  62363. this._soundSource.disconnect();
  62364. this._soundSource = null;
  62365. }
  62366. this._audioBuffer = null;
  62367. if (this._htmlAudioElement) {
  62368. this._htmlAudioElement.pause();
  62369. this._htmlAudioElement.src = "";
  62370. document.body.removeChild(this._htmlAudioElement);
  62371. }
  62372. if (this._connectedMesh && this._registerFunc) {
  62373. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62374. this._connectedMesh = null;
  62375. }
  62376. }
  62377. };
  62378. Sound.prototype.isReady = function () {
  62379. return this._isReadyToPlay;
  62380. };
  62381. Sound.prototype._soundLoaded = function (audioData) {
  62382. var _this = this;
  62383. if (!BABYLON.Engine.audioEngine.audioContext) {
  62384. return;
  62385. }
  62386. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62387. _this._audioBuffer = buffer;
  62388. _this._isReadyToPlay = true;
  62389. if (_this.autoplay) {
  62390. _this.play();
  62391. }
  62392. if (_this._readyToPlayCallback) {
  62393. _this._readyToPlayCallback();
  62394. }
  62395. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62396. };
  62397. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62398. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62399. this._audioBuffer = audioBuffer;
  62400. this._isReadyToPlay = true;
  62401. }
  62402. };
  62403. Sound.prototype.updateOptions = function (options) {
  62404. if (options) {
  62405. this.loop = options.loop || this.loop;
  62406. this.maxDistance = options.maxDistance || this.maxDistance;
  62407. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62408. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62409. this.refDistance = options.refDistance || this.refDistance;
  62410. this.distanceModel = options.distanceModel || this.distanceModel;
  62411. this._playbackRate = options.playbackRate || this._playbackRate;
  62412. this._updateSpatialParameters();
  62413. if (this.isPlaying) {
  62414. if (this._streaming) {
  62415. this._htmlAudioElement.playbackRate = this._playbackRate;
  62416. }
  62417. else {
  62418. if (this._soundSource) {
  62419. this._soundSource.playbackRate.value = this._playbackRate;
  62420. }
  62421. }
  62422. }
  62423. }
  62424. };
  62425. Sound.prototype._createSpatialParameters = function () {
  62426. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62427. if (this._scene.headphone) {
  62428. this._panningModel = "HRTF";
  62429. }
  62430. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62431. this._updateSpatialParameters();
  62432. this._soundPanner.connect(this._ouputAudioNode);
  62433. this._inputAudioNode = this._soundPanner;
  62434. }
  62435. };
  62436. Sound.prototype._updateSpatialParameters = function () {
  62437. if (this.spatialSound && this._soundPanner) {
  62438. if (this.useCustomAttenuation) {
  62439. // Tricks to disable in a way embedded Web Audio attenuation
  62440. this._soundPanner.distanceModel = "linear";
  62441. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62442. this._soundPanner.refDistance = 1;
  62443. this._soundPanner.rolloffFactor = 1;
  62444. this._soundPanner.panningModel = this._panningModel;
  62445. }
  62446. else {
  62447. this._soundPanner.distanceModel = this.distanceModel;
  62448. this._soundPanner.maxDistance = this.maxDistance;
  62449. this._soundPanner.refDistance = this.refDistance;
  62450. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62451. this._soundPanner.panningModel = this._panningModel;
  62452. }
  62453. }
  62454. };
  62455. Sound.prototype.switchPanningModelToHRTF = function () {
  62456. this._panningModel = "HRTF";
  62457. this._switchPanningModel();
  62458. };
  62459. Sound.prototype.switchPanningModelToEqualPower = function () {
  62460. this._panningModel = "equalpower";
  62461. this._switchPanningModel();
  62462. };
  62463. Sound.prototype._switchPanningModel = function () {
  62464. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62465. this._soundPanner.panningModel = this._panningModel;
  62466. }
  62467. };
  62468. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62469. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62470. if (this._isOutputConnected) {
  62471. this._ouputAudioNode.disconnect();
  62472. }
  62473. this._ouputAudioNode.connect(soundTrackAudioNode);
  62474. this._isOutputConnected = true;
  62475. }
  62476. };
  62477. /**
  62478. * Transform this sound into a directional source
  62479. * @param coneInnerAngle Size of the inner cone in degree
  62480. * @param coneOuterAngle Size of the outer cone in degree
  62481. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62482. */
  62483. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62484. if (coneOuterAngle < coneInnerAngle) {
  62485. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62486. return;
  62487. }
  62488. this._coneInnerAngle = coneInnerAngle;
  62489. this._coneOuterAngle = coneOuterAngle;
  62490. this._coneOuterGain = coneOuterGain;
  62491. this._isDirectional = true;
  62492. if (this.isPlaying && this.loop) {
  62493. this.stop();
  62494. this.play();
  62495. }
  62496. };
  62497. Sound.prototype.setPosition = function (newPosition) {
  62498. this._position = newPosition;
  62499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62500. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62501. }
  62502. };
  62503. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62504. this._localDirection = newLocalDirection;
  62505. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62506. this._updateDirection();
  62507. }
  62508. };
  62509. Sound.prototype._updateDirection = function () {
  62510. if (!this._connectedMesh || !this._soundPanner) {
  62511. return;
  62512. }
  62513. var mat = this._connectedMesh.getWorldMatrix();
  62514. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62515. direction.normalize();
  62516. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62517. };
  62518. Sound.prototype.updateDistanceFromListener = function () {
  62519. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62520. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62521. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62522. }
  62523. };
  62524. Sound.prototype.setAttenuationFunction = function (callback) {
  62525. this._customAttenuationFunction = callback;
  62526. };
  62527. /**
  62528. * Play the sound
  62529. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62530. * @param offset (optional) Start the sound setting it at a specific time
  62531. */
  62532. Sound.prototype.play = function (time, offset) {
  62533. var _this = this;
  62534. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62535. try {
  62536. if (this._startOffset < 0) {
  62537. time = -this._startOffset;
  62538. this._startOffset = 0;
  62539. }
  62540. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62541. if (!this._soundSource || !this._streamingSource) {
  62542. if (this.spatialSound && this._soundPanner) {
  62543. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62544. if (this._isDirectional) {
  62545. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62546. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62547. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62548. if (this._connectedMesh) {
  62549. this._updateDirection();
  62550. }
  62551. else {
  62552. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62553. }
  62554. }
  62555. }
  62556. }
  62557. if (this._streaming) {
  62558. if (!this._streamingSource) {
  62559. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62560. this._htmlAudioElement.onended = function () { _this._onended(); };
  62561. this._htmlAudioElement.playbackRate = this._playbackRate;
  62562. }
  62563. this._streamingSource.disconnect();
  62564. this._streamingSource.connect(this._inputAudioNode);
  62565. this._htmlAudioElement.play();
  62566. }
  62567. else {
  62568. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62569. this._soundSource.buffer = this._audioBuffer;
  62570. this._soundSource.connect(this._inputAudioNode);
  62571. this._soundSource.loop = this.loop;
  62572. this._soundSource.playbackRate.value = this._playbackRate;
  62573. this._soundSource.onended = function () { _this._onended(); };
  62574. if (this._soundSource.buffer) {
  62575. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62576. }
  62577. }
  62578. this._startTime = startTime;
  62579. this.isPlaying = true;
  62580. this.isPaused = false;
  62581. }
  62582. catch (ex) {
  62583. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62584. }
  62585. }
  62586. };
  62587. Sound.prototype._onended = function () {
  62588. this.isPlaying = false;
  62589. if (this.onended) {
  62590. this.onended();
  62591. }
  62592. };
  62593. /**
  62594. * Stop the sound
  62595. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62596. */
  62597. Sound.prototype.stop = function (time) {
  62598. if (this.isPlaying) {
  62599. if (this._streaming) {
  62600. this._htmlAudioElement.pause();
  62601. // Test needed for Firefox or it will generate an Invalid State Error
  62602. if (this._htmlAudioElement.currentTime > 0) {
  62603. this._htmlAudioElement.currentTime = 0;
  62604. }
  62605. }
  62606. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62607. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62608. this._soundSource.stop(stopTime);
  62609. this._soundSource.onended = function () { };
  62610. if (!this.isPaused) {
  62611. this._startOffset = 0;
  62612. }
  62613. }
  62614. this.isPlaying = false;
  62615. }
  62616. };
  62617. Sound.prototype.pause = function () {
  62618. if (this.isPlaying) {
  62619. this.isPaused = true;
  62620. if (this._streaming) {
  62621. this._htmlAudioElement.pause();
  62622. }
  62623. else if (BABYLON.Engine.audioEngine.audioContext) {
  62624. this.stop(0);
  62625. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62626. }
  62627. }
  62628. };
  62629. Sound.prototype.setVolume = function (newVolume, time) {
  62630. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62631. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62632. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62633. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62634. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62635. }
  62636. else {
  62637. this._soundGain.gain.value = newVolume;
  62638. }
  62639. }
  62640. this._volume = newVolume;
  62641. };
  62642. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62643. this._playbackRate = newPlaybackRate;
  62644. if (this.isPlaying) {
  62645. if (this._streaming) {
  62646. this._htmlAudioElement.playbackRate = this._playbackRate;
  62647. }
  62648. else if (this._soundSource) {
  62649. this._soundSource.playbackRate.value = this._playbackRate;
  62650. }
  62651. }
  62652. };
  62653. Sound.prototype.getVolume = function () {
  62654. return this._volume;
  62655. };
  62656. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62657. var _this = this;
  62658. if (this._connectedMesh && this._registerFunc) {
  62659. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62660. this._registerFunc = null;
  62661. }
  62662. this._connectedMesh = meshToConnectTo;
  62663. if (!this.spatialSound) {
  62664. this.spatialSound = true;
  62665. this._createSpatialParameters();
  62666. if (this.isPlaying && this.loop) {
  62667. this.stop();
  62668. this.play();
  62669. }
  62670. }
  62671. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62672. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62673. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62674. };
  62675. Sound.prototype.detachFromMesh = function () {
  62676. if (this._connectedMesh && this._registerFunc) {
  62677. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62678. this._registerFunc = null;
  62679. this._connectedMesh = null;
  62680. }
  62681. };
  62682. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62683. if (!node.getBoundingInfo) {
  62684. return;
  62685. }
  62686. var mesh = node;
  62687. var boundingInfo = mesh.getBoundingInfo();
  62688. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62689. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62690. this._updateDirection();
  62691. }
  62692. };
  62693. Sound.prototype.clone = function () {
  62694. var _this = this;
  62695. if (!this._streaming) {
  62696. var setBufferAndRun = function () {
  62697. if (_this._isReadyToPlay) {
  62698. clonedSound._audioBuffer = _this.getAudioBuffer();
  62699. clonedSound._isReadyToPlay = true;
  62700. if (clonedSound.autoplay) {
  62701. clonedSound.play();
  62702. }
  62703. }
  62704. else {
  62705. window.setTimeout(setBufferAndRun, 300);
  62706. }
  62707. };
  62708. var currentOptions = {
  62709. autoplay: this.autoplay, loop: this.loop,
  62710. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62711. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62712. refDistance: this.refDistance, distanceModel: this.distanceModel
  62713. };
  62714. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62715. if (this.useCustomAttenuation) {
  62716. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62717. }
  62718. clonedSound.setPosition(this._position);
  62719. clonedSound.setPlaybackRate(this._playbackRate);
  62720. setBufferAndRun();
  62721. return clonedSound;
  62722. }
  62723. // Can't clone a streaming sound
  62724. else {
  62725. return null;
  62726. }
  62727. };
  62728. Sound.prototype.getAudioBuffer = function () {
  62729. return this._audioBuffer;
  62730. };
  62731. Sound.prototype.serialize = function () {
  62732. var serializationObject = {
  62733. name: this.name,
  62734. url: this.name,
  62735. autoplay: this.autoplay,
  62736. loop: this.loop,
  62737. volume: this._volume,
  62738. spatialSound: this.spatialSound,
  62739. maxDistance: this.maxDistance,
  62740. rolloffFactor: this.rolloffFactor,
  62741. refDistance: this.refDistance,
  62742. distanceModel: this.distanceModel,
  62743. playbackRate: this._playbackRate,
  62744. panningModel: this._panningModel,
  62745. soundTrackId: this.soundTrackId
  62746. };
  62747. if (this.spatialSound) {
  62748. if (this._connectedMesh)
  62749. serializationObject.connectedMeshId = this._connectedMesh.id;
  62750. serializationObject.position = this._position.asArray();
  62751. serializationObject.refDistance = this.refDistance;
  62752. serializationObject.distanceModel = this.distanceModel;
  62753. serializationObject.isDirectional = this._isDirectional;
  62754. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62755. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62756. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62757. serializationObject.coneOuterGain = this._coneOuterGain;
  62758. }
  62759. return serializationObject;
  62760. };
  62761. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62762. var soundName = parsedSound.name;
  62763. var soundUrl;
  62764. if (parsedSound.url) {
  62765. soundUrl = rootUrl + parsedSound.url;
  62766. }
  62767. else {
  62768. soundUrl = rootUrl + soundName;
  62769. }
  62770. var options = {
  62771. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62772. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62773. rolloffFactor: parsedSound.rolloffFactor,
  62774. refDistance: parsedSound.refDistance,
  62775. distanceModel: parsedSound.distanceModel,
  62776. playbackRate: parsedSound.playbackRate
  62777. };
  62778. var newSound;
  62779. if (!sourceSound) {
  62780. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62781. scene._addPendingData(newSound);
  62782. }
  62783. else {
  62784. var setBufferAndRun = function () {
  62785. if (sourceSound._isReadyToPlay) {
  62786. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62787. newSound._isReadyToPlay = true;
  62788. if (newSound.autoplay) {
  62789. newSound.play();
  62790. }
  62791. }
  62792. else {
  62793. window.setTimeout(setBufferAndRun, 300);
  62794. }
  62795. };
  62796. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62797. setBufferAndRun();
  62798. }
  62799. if (parsedSound.position) {
  62800. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62801. newSound.setPosition(soundPosition);
  62802. }
  62803. if (parsedSound.isDirectional) {
  62804. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62805. if (parsedSound.localDirectionToMesh) {
  62806. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62807. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62808. }
  62809. }
  62810. if (parsedSound.connectedMeshId) {
  62811. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62812. if (connectedMesh) {
  62813. newSound.attachToMesh(connectedMesh);
  62814. }
  62815. }
  62816. return newSound;
  62817. };
  62818. return Sound;
  62819. }());
  62820. BABYLON.Sound = Sound;
  62821. })(BABYLON || (BABYLON = {}));
  62822. //# sourceMappingURL=babylon.sound.js.map
  62823. var BABYLON;
  62824. (function (BABYLON) {
  62825. var SoundTrack = /** @class */ (function () {
  62826. function SoundTrack(scene, options) {
  62827. this.id = -1;
  62828. this._isMainTrack = false;
  62829. this._isInitialized = false;
  62830. this._scene = scene;
  62831. this.soundCollection = new Array();
  62832. this._options = options;
  62833. if (!this._isMainTrack) {
  62834. this._scene.soundTracks.push(this);
  62835. this.id = this._scene.soundTracks.length - 1;
  62836. }
  62837. }
  62838. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62839. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62840. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62841. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62842. if (this._options) {
  62843. if (this._options.volume) {
  62844. this._outputAudioNode.gain.value = this._options.volume;
  62845. }
  62846. if (this._options.mainTrack) {
  62847. this._isMainTrack = this._options.mainTrack;
  62848. }
  62849. }
  62850. this._isInitialized = true;
  62851. }
  62852. };
  62853. SoundTrack.prototype.dispose = function () {
  62854. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62855. if (this._connectedAnalyser) {
  62856. this._connectedAnalyser.stopDebugCanvas();
  62857. }
  62858. while (this.soundCollection.length) {
  62859. this.soundCollection[0].dispose();
  62860. }
  62861. if (this._outputAudioNode) {
  62862. this._outputAudioNode.disconnect();
  62863. }
  62864. this._outputAudioNode = null;
  62865. }
  62866. };
  62867. SoundTrack.prototype.AddSound = function (sound) {
  62868. if (!this._isInitialized) {
  62869. this._initializeSoundTrackAudioGraph();
  62870. }
  62871. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62872. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62873. }
  62874. if (sound.soundTrackId) {
  62875. if (sound.soundTrackId === -1) {
  62876. this._scene.mainSoundTrack.RemoveSound(sound);
  62877. }
  62878. else {
  62879. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62880. }
  62881. }
  62882. this.soundCollection.push(sound);
  62883. sound.soundTrackId = this.id;
  62884. };
  62885. SoundTrack.prototype.RemoveSound = function (sound) {
  62886. var index = this.soundCollection.indexOf(sound);
  62887. if (index !== -1) {
  62888. this.soundCollection.splice(index, 1);
  62889. }
  62890. };
  62891. SoundTrack.prototype.setVolume = function (newVolume) {
  62892. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62893. this._outputAudioNode.gain.value = newVolume;
  62894. }
  62895. };
  62896. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62897. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62898. for (var i = 0; i < this.soundCollection.length; i++) {
  62899. this.soundCollection[i].switchPanningModelToHRTF();
  62900. }
  62901. }
  62902. };
  62903. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62904. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62905. for (var i = 0; i < this.soundCollection.length; i++) {
  62906. this.soundCollection[i].switchPanningModelToEqualPower();
  62907. }
  62908. }
  62909. };
  62910. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62911. if (this._connectedAnalyser) {
  62912. this._connectedAnalyser.stopDebugCanvas();
  62913. }
  62914. this._connectedAnalyser = analyser;
  62915. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62916. this._outputAudioNode.disconnect();
  62917. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62918. }
  62919. };
  62920. return SoundTrack;
  62921. }());
  62922. BABYLON.SoundTrack = SoundTrack;
  62923. })(BABYLON || (BABYLON = {}));
  62924. //# sourceMappingURL=babylon.soundtrack.js.map
  62925. var BABYLON;
  62926. (function (BABYLON) {
  62927. /**
  62928. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62929. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62930. */
  62931. var Analyser = /** @class */ (function () {
  62932. /**
  62933. * Creates a new analyser
  62934. * @param scene defines hosting scene
  62935. */
  62936. function Analyser(scene) {
  62937. /**
  62938. * Gets or sets the smoothing
  62939. * @ignorenaming
  62940. */
  62941. this.SMOOTHING = 0.75;
  62942. /**
  62943. * Gets or sets the FFT table size
  62944. * @ignorenaming
  62945. */
  62946. this.FFT_SIZE = 512;
  62947. /**
  62948. * Gets or sets the bar graph amplitude
  62949. * @ignorenaming
  62950. */
  62951. this.BARGRAPHAMPLITUDE = 256;
  62952. /**
  62953. * Gets or sets the position of the debug canvas
  62954. * @ignorenaming
  62955. */
  62956. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62957. /**
  62958. * Gets or sets the debug canvas size
  62959. * @ignorenaming
  62960. */
  62961. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62962. this._scene = scene;
  62963. this._audioEngine = BABYLON.Engine.audioEngine;
  62964. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62965. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62966. this._webAudioAnalyser.minDecibels = -140;
  62967. this._webAudioAnalyser.maxDecibels = 0;
  62968. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62969. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62970. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62971. }
  62972. }
  62973. /**
  62974. * Get the number of data values you will have to play with for the visualization
  62975. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62976. * @returns a number
  62977. */
  62978. Analyser.prototype.getFrequencyBinCount = function () {
  62979. if (this._audioEngine.canUseWebAudio) {
  62980. return this._webAudioAnalyser.frequencyBinCount;
  62981. }
  62982. else {
  62983. return 0;
  62984. }
  62985. };
  62986. /**
  62987. * Gets the current frequency data as a byte array
  62988. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62989. * @returns a Uint8Array
  62990. */
  62991. Analyser.prototype.getByteFrequencyData = function () {
  62992. if (this._audioEngine.canUseWebAudio) {
  62993. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62994. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62995. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62996. }
  62997. return this._byteFreqs;
  62998. };
  62999. /**
  63000. * Gets the current waveform as a byte array
  63001. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63002. * @returns a Uint8Array
  63003. */
  63004. Analyser.prototype.getByteTimeDomainData = function () {
  63005. if (this._audioEngine.canUseWebAudio) {
  63006. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63007. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63008. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63009. }
  63010. return this._byteTime;
  63011. };
  63012. /**
  63013. * Gets the current frequency data as a float array
  63014. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63015. * @returns a Float32Array
  63016. */
  63017. Analyser.prototype.getFloatFrequencyData = function () {
  63018. if (this._audioEngine.canUseWebAudio) {
  63019. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63020. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63021. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63022. }
  63023. return this._floatFreqs;
  63024. };
  63025. /**
  63026. * Renders the debug canvas
  63027. */
  63028. Analyser.prototype.drawDebugCanvas = function () {
  63029. var _this = this;
  63030. if (this._audioEngine.canUseWebAudio) {
  63031. if (!this._debugCanvas) {
  63032. this._debugCanvas = document.createElement("canvas");
  63033. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63034. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63035. this._debugCanvas.style.position = "absolute";
  63036. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63037. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63038. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63039. document.body.appendChild(this._debugCanvas);
  63040. this._registerFunc = function () {
  63041. _this.drawDebugCanvas();
  63042. };
  63043. this._scene.registerBeforeRender(this._registerFunc);
  63044. }
  63045. if (this._registerFunc && this._debugCanvasContext) {
  63046. var workingArray = this.getByteFrequencyData();
  63047. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63048. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63049. // Draw the frequency domain chart.
  63050. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63051. var value = workingArray[i];
  63052. var percent = value / this.BARGRAPHAMPLITUDE;
  63053. var height = this.DEBUGCANVASSIZE.height * percent;
  63054. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63055. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63056. var hue = i / this.getFrequencyBinCount() * 360;
  63057. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63058. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63059. }
  63060. }
  63061. }
  63062. };
  63063. /**
  63064. * Stops rendering the debug canvas and removes it
  63065. */
  63066. Analyser.prototype.stopDebugCanvas = function () {
  63067. if (this._debugCanvas) {
  63068. if (this._registerFunc) {
  63069. this._scene.unregisterBeforeRender(this._registerFunc);
  63070. this._registerFunc = null;
  63071. }
  63072. document.body.removeChild(this._debugCanvas);
  63073. this._debugCanvas = null;
  63074. this._debugCanvasContext = null;
  63075. }
  63076. };
  63077. /**
  63078. * Connects two audio nodes
  63079. * @param inputAudioNode defines first node to connect
  63080. * @param outputAudioNode defines second node to connect
  63081. */
  63082. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63083. if (this._audioEngine.canUseWebAudio) {
  63084. inputAudioNode.connect(this._webAudioAnalyser);
  63085. this._webAudioAnalyser.connect(outputAudioNode);
  63086. }
  63087. };
  63088. /**
  63089. * Releases all associated resources
  63090. */
  63091. Analyser.prototype.dispose = function () {
  63092. if (this._audioEngine.canUseWebAudio) {
  63093. this._webAudioAnalyser.disconnect();
  63094. }
  63095. };
  63096. return Analyser;
  63097. }());
  63098. BABYLON.Analyser = Analyser;
  63099. })(BABYLON || (BABYLON = {}));
  63100. //# sourceMappingURL=babylon.analyser.js.map
  63101. var BABYLON;
  63102. (function (BABYLON) {
  63103. var CubeTexture = /** @class */ (function (_super) {
  63104. __extends(CubeTexture, _super);
  63105. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63106. if (extensions === void 0) { extensions = null; }
  63107. if (noMipmap === void 0) { noMipmap = false; }
  63108. if (files === void 0) { files = null; }
  63109. if (onLoad === void 0) { onLoad = null; }
  63110. if (onError === void 0) { onError = null; }
  63111. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63112. if (prefiltered === void 0) { prefiltered = false; }
  63113. if (forcedExtension === void 0) { forcedExtension = null; }
  63114. var _this = _super.call(this, scene) || this;
  63115. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63116. /**
  63117. * Gets or sets the center of the bounding box associated with the cube texture
  63118. * It must define where the camera used to render the texture was set
  63119. */
  63120. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63121. _this._rotationY = 0;
  63122. _this.name = rootUrl;
  63123. _this.url = rootUrl;
  63124. _this._noMipmap = noMipmap;
  63125. _this.hasAlpha = false;
  63126. _this._format = format;
  63127. _this._prefiltered = prefiltered;
  63128. _this.isCube = true;
  63129. _this._textureMatrix = BABYLON.Matrix.Identity();
  63130. if (prefiltered) {
  63131. _this.gammaSpace = false;
  63132. }
  63133. if (!rootUrl && !files) {
  63134. return _this;
  63135. }
  63136. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63137. var lastDot = rootUrl.lastIndexOf(".");
  63138. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63139. var isDDS = (extension === ".dds");
  63140. if (!files) {
  63141. if (!isDDS && !extensions) {
  63142. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63143. }
  63144. files = [];
  63145. if (extensions) {
  63146. for (var index = 0; index < extensions.length; index++) {
  63147. files.push(rootUrl + extensions[index]);
  63148. }
  63149. }
  63150. }
  63151. _this._files = files;
  63152. if (!_this._texture) {
  63153. if (!scene.useDelayedTextureLoading) {
  63154. if (prefiltered) {
  63155. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63156. }
  63157. else {
  63158. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63159. }
  63160. }
  63161. else {
  63162. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63163. }
  63164. }
  63165. else if (onLoad) {
  63166. if (_this._texture.isReady) {
  63167. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63168. }
  63169. else {
  63170. _this._texture.onLoadedObservable.add(onLoad);
  63171. }
  63172. }
  63173. return _this;
  63174. }
  63175. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63176. get: function () {
  63177. return this._boundingBoxSize;
  63178. },
  63179. /**
  63180. * Gets or sets the size of the bounding box associated with the cube texture
  63181. * When defined, the cubemap will switch to local mode
  63182. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63183. * @example https://www.babylonjs-playground.com/#RNASML
  63184. */
  63185. set: function (value) {
  63186. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63187. return;
  63188. }
  63189. this._boundingBoxSize = value;
  63190. var scene = this.getScene();
  63191. if (scene) {
  63192. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63193. }
  63194. },
  63195. enumerable: true,
  63196. configurable: true
  63197. });
  63198. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63199. /**
  63200. * Gets texture matrix rotation angle around Y axis radians.
  63201. */
  63202. get: function () {
  63203. return this._rotationY;
  63204. },
  63205. /**
  63206. * Sets texture matrix rotation angle around Y axis in radians.
  63207. */
  63208. set: function (value) {
  63209. this._rotationY = value;
  63210. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63211. },
  63212. enumerable: true,
  63213. configurable: true
  63214. });
  63215. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63216. var rootUrlKey = "";
  63217. files.forEach(function (url) { return rootUrlKey += url; });
  63218. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63219. };
  63220. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63221. if (forcedExtension === void 0) { forcedExtension = null; }
  63222. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63223. };
  63224. // Methods
  63225. CubeTexture.prototype.delayLoad = function () {
  63226. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63227. return;
  63228. }
  63229. var scene = this.getScene();
  63230. if (!scene) {
  63231. return;
  63232. }
  63233. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63234. this._texture = this._getFromCache(this.url, this._noMipmap);
  63235. if (!this._texture) {
  63236. if (this._prefiltered) {
  63237. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63238. }
  63239. else {
  63240. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63241. }
  63242. }
  63243. };
  63244. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63245. return this._textureMatrix;
  63246. };
  63247. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63248. this._textureMatrix = value;
  63249. };
  63250. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63251. var texture = BABYLON.SerializationHelper.Parse(function () {
  63252. var prefiltered = false;
  63253. if (parsedTexture.prefiltered) {
  63254. prefiltered = parsedTexture.prefiltered;
  63255. }
  63256. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63257. }, parsedTexture, scene);
  63258. // Local Cubemaps
  63259. if (parsedTexture.boundingBoxPosition) {
  63260. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63261. }
  63262. if (parsedTexture.boundingBoxSize) {
  63263. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63264. }
  63265. // Animations
  63266. if (parsedTexture.animations) {
  63267. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63268. var parsedAnimation = parsedTexture.animations[animationIndex];
  63269. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63270. }
  63271. }
  63272. return texture;
  63273. };
  63274. CubeTexture.prototype.clone = function () {
  63275. var _this = this;
  63276. return BABYLON.SerializationHelper.Clone(function () {
  63277. var scene = _this.getScene();
  63278. if (!scene) {
  63279. return _this;
  63280. }
  63281. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63282. }, this);
  63283. };
  63284. __decorate([
  63285. BABYLON.serialize("rotationY")
  63286. ], CubeTexture.prototype, "_rotationY", void 0);
  63287. return CubeTexture;
  63288. }(BABYLON.BaseTexture));
  63289. BABYLON.CubeTexture = CubeTexture;
  63290. })(BABYLON || (BABYLON = {}));
  63291. //# sourceMappingURL=babylon.cubeTexture.js.map
  63292. var BABYLON;
  63293. (function (BABYLON) {
  63294. var RenderTargetTexture = /** @class */ (function (_super) {
  63295. __extends(RenderTargetTexture, _super);
  63296. /**
  63297. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63298. * or used a shadow, depth texture...
  63299. * @param name The friendly name of the texture
  63300. * @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)
  63301. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63302. * @param generateMipMaps True if mip maps need to be generated after render.
  63303. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63304. * @param type The type of the buffer in the RTT (int, half float, float...)
  63305. * @param isCube True if a cube texture needs to be created
  63306. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63307. * @param generateDepthBuffer True to generate a depth buffer
  63308. * @param generateStencilBuffer True to generate a stencil buffer
  63309. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63310. */
  63311. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63312. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63313. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63314. if (isCube === void 0) { isCube = false; }
  63315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63316. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63317. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63318. if (isMulti === void 0) { isMulti = false; }
  63319. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63320. _this.isCube = isCube;
  63321. /**
  63322. * Use this list to define the list of mesh you want to render.
  63323. */
  63324. _this.renderList = new Array();
  63325. _this.renderParticles = true;
  63326. _this.renderSprites = false;
  63327. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63328. _this.ignoreCameraViewport = false;
  63329. // Events
  63330. /**
  63331. * An event triggered when the texture is unbind.
  63332. */
  63333. _this.onBeforeBindObservable = new BABYLON.Observable();
  63334. /**
  63335. * An event triggered when the texture is unbind.
  63336. */
  63337. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63338. /**
  63339. * An event triggered before rendering the texture
  63340. */
  63341. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63342. /**
  63343. * An event triggered after rendering the texture
  63344. */
  63345. _this.onAfterRenderObservable = new BABYLON.Observable();
  63346. /**
  63347. * An event triggered after the texture clear
  63348. */
  63349. _this.onClearObservable = new BABYLON.Observable();
  63350. _this._currentRefreshId = -1;
  63351. _this._refreshRate = 1;
  63352. _this._samples = 1;
  63353. /**
  63354. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63355. * It must define where the camera used to render the texture is set
  63356. */
  63357. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63358. scene = _this.getScene();
  63359. if (!scene) {
  63360. return _this;
  63361. }
  63362. _this._engine = scene.getEngine();
  63363. _this.name = name;
  63364. _this.isRenderTarget = true;
  63365. _this._initialSizeParameter = size;
  63366. _this._processSizeParameter(size);
  63367. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63368. });
  63369. _this._generateMipMaps = generateMipMaps ? true : false;
  63370. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63371. // Rendering groups
  63372. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63373. if (isMulti) {
  63374. return _this;
  63375. }
  63376. _this._renderTargetOptions = {
  63377. generateMipMaps: generateMipMaps,
  63378. type: type,
  63379. samplingMode: samplingMode,
  63380. generateDepthBuffer: generateDepthBuffer,
  63381. generateStencilBuffer: generateStencilBuffer
  63382. };
  63383. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63384. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63385. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63386. }
  63387. if (isCube) {
  63388. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63389. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63390. _this._textureMatrix = BABYLON.Matrix.Identity();
  63391. }
  63392. else {
  63393. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63394. }
  63395. return _this;
  63396. }
  63397. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63398. get: function () {
  63399. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63400. },
  63401. enumerable: true,
  63402. configurable: true
  63403. });
  63404. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63405. get: function () {
  63406. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63407. },
  63408. enumerable: true,
  63409. configurable: true
  63410. });
  63411. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63412. get: function () {
  63413. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63414. },
  63415. enumerable: true,
  63416. configurable: true
  63417. });
  63418. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63419. set: function (callback) {
  63420. if (this._onAfterUnbindObserver) {
  63421. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63422. }
  63423. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63424. },
  63425. enumerable: true,
  63426. configurable: true
  63427. });
  63428. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63429. set: function (callback) {
  63430. if (this._onBeforeRenderObserver) {
  63431. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63432. }
  63433. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63434. },
  63435. enumerable: true,
  63436. configurable: true
  63437. });
  63438. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63439. set: function (callback) {
  63440. if (this._onAfterRenderObserver) {
  63441. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63442. }
  63443. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63444. },
  63445. enumerable: true,
  63446. configurable: true
  63447. });
  63448. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63449. set: function (callback) {
  63450. if (this._onClearObserver) {
  63451. this.onClearObservable.remove(this._onClearObserver);
  63452. }
  63453. this._onClearObserver = this.onClearObservable.add(callback);
  63454. },
  63455. enumerable: true,
  63456. configurable: true
  63457. });
  63458. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63459. get: function () {
  63460. return this._renderTargetOptions;
  63461. },
  63462. enumerable: true,
  63463. configurable: true
  63464. });
  63465. RenderTargetTexture.prototype._onRatioRescale = function () {
  63466. if (this._sizeRatio) {
  63467. this.resize(this._initialSizeParameter);
  63468. }
  63469. };
  63470. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63471. get: function () {
  63472. return this._boundingBoxSize;
  63473. },
  63474. /**
  63475. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63476. * When defined, the cubemap will switch to local mode
  63477. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63478. * @example https://www.babylonjs-playground.com/#RNASML
  63479. */
  63480. set: function (value) {
  63481. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63482. return;
  63483. }
  63484. this._boundingBoxSize = value;
  63485. var scene = this.getScene();
  63486. if (scene) {
  63487. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63488. }
  63489. },
  63490. enumerable: true,
  63491. configurable: true
  63492. });
  63493. /**
  63494. * Creates a depth stencil texture.
  63495. * This is only available in WebGL 2 or with the depth texture extension available.
  63496. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63497. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63498. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63499. */
  63500. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63501. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63502. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63503. if (generateStencil === void 0) { generateStencil = false; }
  63504. if (!this.getScene()) {
  63505. return;
  63506. }
  63507. var engine = this.getScene().getEngine();
  63508. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63509. bilinearFiltering: bilinearFiltering,
  63510. comparisonFunction: comparisonFunction,
  63511. generateStencil: generateStencil,
  63512. isCube: this.isCube
  63513. });
  63514. engine.setFrameBufferDepthStencilTexture(this);
  63515. };
  63516. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63517. if (size.ratio) {
  63518. this._sizeRatio = size.ratio;
  63519. this._size = {
  63520. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63521. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63522. };
  63523. }
  63524. else {
  63525. this._size = size;
  63526. }
  63527. };
  63528. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63529. get: function () {
  63530. return this._samples;
  63531. },
  63532. set: function (value) {
  63533. if (this._samples === value) {
  63534. return;
  63535. }
  63536. var scene = this.getScene();
  63537. if (!scene) {
  63538. return;
  63539. }
  63540. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63541. },
  63542. enumerable: true,
  63543. configurable: true
  63544. });
  63545. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63546. this._currentRefreshId = -1;
  63547. };
  63548. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63549. get: function () {
  63550. return this._refreshRate;
  63551. },
  63552. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63553. set: function (value) {
  63554. this._refreshRate = value;
  63555. this.resetRefreshCounter();
  63556. },
  63557. enumerable: true,
  63558. configurable: true
  63559. });
  63560. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63561. if (!this._postProcessManager) {
  63562. var scene = this.getScene();
  63563. if (!scene) {
  63564. return;
  63565. }
  63566. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63567. this._postProcesses = new Array();
  63568. }
  63569. this._postProcesses.push(postProcess);
  63570. this._postProcesses[0].autoClear = false;
  63571. };
  63572. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63573. if (!this._postProcesses) {
  63574. return;
  63575. }
  63576. if (dispose) {
  63577. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63578. var postProcess = _a[_i];
  63579. postProcess.dispose();
  63580. }
  63581. }
  63582. this._postProcesses = [];
  63583. };
  63584. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63585. if (!this._postProcesses) {
  63586. return;
  63587. }
  63588. var index = this._postProcesses.indexOf(postProcess);
  63589. if (index === -1) {
  63590. return;
  63591. }
  63592. this._postProcesses.splice(index, 1);
  63593. if (this._postProcesses.length > 0) {
  63594. this._postProcesses[0].autoClear = false;
  63595. }
  63596. };
  63597. RenderTargetTexture.prototype._shouldRender = function () {
  63598. if (this._currentRefreshId === -1) { // At least render once
  63599. this._currentRefreshId = 1;
  63600. return true;
  63601. }
  63602. if (this.refreshRate === this._currentRefreshId) {
  63603. this._currentRefreshId = 1;
  63604. return true;
  63605. }
  63606. this._currentRefreshId++;
  63607. return false;
  63608. };
  63609. RenderTargetTexture.prototype.getRenderSize = function () {
  63610. if (this._size.width) {
  63611. return this._size.width;
  63612. }
  63613. return this._size;
  63614. };
  63615. RenderTargetTexture.prototype.getRenderWidth = function () {
  63616. if (this._size.width) {
  63617. return this._size.width;
  63618. }
  63619. return this._size;
  63620. };
  63621. RenderTargetTexture.prototype.getRenderHeight = function () {
  63622. if (this._size.width) {
  63623. return this._size.height;
  63624. }
  63625. return this._size;
  63626. };
  63627. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63628. get: function () {
  63629. return true;
  63630. },
  63631. enumerable: true,
  63632. configurable: true
  63633. });
  63634. RenderTargetTexture.prototype.scale = function (ratio) {
  63635. var newSize = this.getRenderSize() * ratio;
  63636. this.resize(newSize);
  63637. };
  63638. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63639. if (this.isCube) {
  63640. return this._textureMatrix;
  63641. }
  63642. return _super.prototype.getReflectionTextureMatrix.call(this);
  63643. };
  63644. RenderTargetTexture.prototype.resize = function (size) {
  63645. this.releaseInternalTexture();
  63646. var scene = this.getScene();
  63647. if (!scene) {
  63648. return;
  63649. }
  63650. this._processSizeParameter(size);
  63651. if (this.isCube) {
  63652. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63653. }
  63654. else {
  63655. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63656. }
  63657. };
  63658. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63659. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63660. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63661. var scene = this.getScene();
  63662. if (!scene) {
  63663. return;
  63664. }
  63665. var engine = scene.getEngine();
  63666. if (this.useCameraPostProcesses !== undefined) {
  63667. useCameraPostProcess = this.useCameraPostProcesses;
  63668. }
  63669. if (this._waitingRenderList) {
  63670. this.renderList = [];
  63671. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63672. var id = this._waitingRenderList[index];
  63673. var mesh_1 = scene.getMeshByID(id);
  63674. if (mesh_1) {
  63675. this.renderList.push(mesh_1);
  63676. }
  63677. }
  63678. delete this._waitingRenderList;
  63679. }
  63680. // Is predicate defined?
  63681. if (this.renderListPredicate) {
  63682. if (this.renderList) {
  63683. this.renderList.splice(0); // Clear previous renderList
  63684. }
  63685. else {
  63686. this.renderList = [];
  63687. }
  63688. var scene = this.getScene();
  63689. if (!scene) {
  63690. return;
  63691. }
  63692. var sceneMeshes = scene.meshes;
  63693. for (var index = 0; index < sceneMeshes.length; index++) {
  63694. var mesh = sceneMeshes[index];
  63695. if (this.renderListPredicate(mesh)) {
  63696. this.renderList.push(mesh);
  63697. }
  63698. }
  63699. }
  63700. this.onBeforeBindObservable.notifyObservers(this);
  63701. // Set custom projection.
  63702. // Needs to be before binding to prevent changing the aspect ratio.
  63703. var camera;
  63704. if (this.activeCamera) {
  63705. camera = this.activeCamera;
  63706. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63707. if (this.activeCamera !== scene.activeCamera) {
  63708. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63709. }
  63710. }
  63711. else {
  63712. camera = scene.activeCamera;
  63713. if (camera) {
  63714. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63715. }
  63716. }
  63717. // Prepare renderingManager
  63718. this._renderingManager.reset();
  63719. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63720. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63721. var sceneRenderId = scene.getRenderId();
  63722. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63723. var mesh = currentRenderList[meshIndex];
  63724. if (mesh) {
  63725. if (!mesh.isReady(this.refreshRate === 0)) {
  63726. this.resetRefreshCounter();
  63727. continue;
  63728. }
  63729. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63730. var isMasked = void 0;
  63731. if (!this.renderList && camera) {
  63732. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63733. }
  63734. else {
  63735. isMasked = false;
  63736. }
  63737. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63738. mesh._activate(sceneRenderId);
  63739. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63740. var subMesh = mesh.subMeshes[subIndex];
  63741. scene._activeIndices.addCount(subMesh.indexCount, false);
  63742. this._renderingManager.dispatch(subMesh, mesh);
  63743. }
  63744. }
  63745. }
  63746. }
  63747. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63748. var particleSystem = scene.particleSystems[particleIndex];
  63749. var emitter = particleSystem.emitter;
  63750. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63751. continue;
  63752. }
  63753. if (currentRenderList.indexOf(emitter) >= 0) {
  63754. this._renderingManager.dispatchParticles(particleSystem);
  63755. }
  63756. }
  63757. if (this.isCube) {
  63758. for (var face = 0; face < 6; face++) {
  63759. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63760. scene.incrementRenderId();
  63761. scene.resetCachedMaterial();
  63762. }
  63763. }
  63764. else {
  63765. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63766. }
  63767. this.onAfterUnbindObservable.notifyObservers(this);
  63768. if (scene.activeCamera) {
  63769. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63770. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63771. }
  63772. engine.setViewport(scene.activeCamera.viewport);
  63773. }
  63774. scene.resetCachedMaterial();
  63775. };
  63776. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63777. var minimum = 128;
  63778. var x = renderDimension * scale;
  63779. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63780. // Ensure we don't exceed the render dimension (while staying POT)
  63781. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63782. };
  63783. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63784. var _this = this;
  63785. if (!this._texture) {
  63786. return;
  63787. }
  63788. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63789. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63790. });
  63791. };
  63792. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63793. var scene = this.getScene();
  63794. if (!scene) {
  63795. return;
  63796. }
  63797. var engine = scene.getEngine();
  63798. if (!this._texture) {
  63799. return;
  63800. }
  63801. // Bind
  63802. if (this._postProcessManager) {
  63803. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63804. }
  63805. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63806. if (this._texture) {
  63807. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63808. }
  63809. }
  63810. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63811. // Clear
  63812. if (this.onClearObservable.hasObservers()) {
  63813. this.onClearObservable.notifyObservers(engine);
  63814. }
  63815. else {
  63816. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63817. }
  63818. if (!this._doNotChangeAspectRatio) {
  63819. scene.updateTransformMatrix(true);
  63820. }
  63821. // Render
  63822. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63823. if (this._postProcessManager) {
  63824. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63825. }
  63826. else if (useCameraPostProcess) {
  63827. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63828. }
  63829. if (!this._doNotChangeAspectRatio) {
  63830. scene.updateTransformMatrix(true);
  63831. }
  63832. // Dump ?
  63833. if (dumpForDebug) {
  63834. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63835. }
  63836. // Unbind
  63837. if (!this.isCube || faceIndex === 5) {
  63838. if (this.isCube) {
  63839. if (faceIndex === 5) {
  63840. engine.generateMipMapsForCubemap(this._texture);
  63841. }
  63842. }
  63843. this.unbindFrameBuffer(engine, faceIndex);
  63844. }
  63845. else {
  63846. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63847. }
  63848. };
  63849. /**
  63850. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63851. * This allowed control for front to back rendering or reversly depending of the special needs.
  63852. *
  63853. * @param renderingGroupId The rendering group id corresponding to its index
  63854. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63855. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63856. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63857. */
  63858. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63859. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63860. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63861. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63862. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63863. };
  63864. /**
  63865. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63866. *
  63867. * @param renderingGroupId The rendering group id corresponding to its index
  63868. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63869. */
  63870. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63871. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63872. };
  63873. RenderTargetTexture.prototype.clone = function () {
  63874. var textureSize = this.getSize();
  63875. 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);
  63876. // Base texture
  63877. newTexture.hasAlpha = this.hasAlpha;
  63878. newTexture.level = this.level;
  63879. // RenderTarget Texture
  63880. newTexture.coordinatesMode = this.coordinatesMode;
  63881. if (this.renderList) {
  63882. newTexture.renderList = this.renderList.slice(0);
  63883. }
  63884. return newTexture;
  63885. };
  63886. RenderTargetTexture.prototype.serialize = function () {
  63887. if (!this.name) {
  63888. return null;
  63889. }
  63890. var serializationObject = _super.prototype.serialize.call(this);
  63891. serializationObject.renderTargetSize = this.getRenderSize();
  63892. serializationObject.renderList = [];
  63893. if (this.renderList) {
  63894. for (var index = 0; index < this.renderList.length; index++) {
  63895. serializationObject.renderList.push(this.renderList[index].id);
  63896. }
  63897. }
  63898. return serializationObject;
  63899. };
  63900. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63901. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63902. var objBuffer = this.getInternalTexture();
  63903. var scene = this.getScene();
  63904. if (objBuffer && scene) {
  63905. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63906. }
  63907. };
  63908. RenderTargetTexture.prototype.dispose = function () {
  63909. if (this._postProcessManager) {
  63910. this._postProcessManager.dispose();
  63911. this._postProcessManager = null;
  63912. }
  63913. this.clearPostProcesses(true);
  63914. if (this._resizeObserver) {
  63915. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63916. this._resizeObserver = null;
  63917. }
  63918. this.renderList = null;
  63919. // Remove from custom render targets
  63920. var scene = this.getScene();
  63921. if (!scene) {
  63922. return;
  63923. }
  63924. var index = scene.customRenderTargets.indexOf(this);
  63925. if (index >= 0) {
  63926. scene.customRenderTargets.splice(index, 1);
  63927. }
  63928. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63929. var camera = _a[_i];
  63930. index = camera.customRenderTargets.indexOf(this);
  63931. if (index >= 0) {
  63932. camera.customRenderTargets.splice(index, 1);
  63933. }
  63934. }
  63935. _super.prototype.dispose.call(this);
  63936. };
  63937. RenderTargetTexture.prototype._rebuild = function () {
  63938. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63939. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63940. }
  63941. if (this._postProcessManager) {
  63942. this._postProcessManager._rebuild();
  63943. }
  63944. };
  63945. /**
  63946. * Clear the info related to rendering groups preventing retention point in material dispose.
  63947. */
  63948. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63949. if (this._renderingManager) {
  63950. this._renderingManager.freeRenderingGroups();
  63951. }
  63952. };
  63953. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63954. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63955. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63956. return RenderTargetTexture;
  63957. }(BABYLON.Texture));
  63958. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63959. })(BABYLON || (BABYLON = {}));
  63960. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63961. var BABYLON;
  63962. (function (BABYLON) {
  63963. ;
  63964. var MultiRenderTarget = /** @class */ (function (_super) {
  63965. __extends(MultiRenderTarget, _super);
  63966. function MultiRenderTarget(name, size, count, scene, options) {
  63967. var _this = this;
  63968. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63969. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63970. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63971. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63972. _this._engine = scene.getEngine();
  63973. if (!_this.isSupported) {
  63974. _this.dispose();
  63975. return;
  63976. }
  63977. var types = [];
  63978. var samplingModes = [];
  63979. for (var i = 0; i < count; i++) {
  63980. if (options && options.types && options.types[i] !== undefined) {
  63981. types.push(options.types[i]);
  63982. }
  63983. else {
  63984. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63985. }
  63986. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63987. samplingModes.push(options.samplingModes[i]);
  63988. }
  63989. else {
  63990. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63991. }
  63992. }
  63993. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63994. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63995. _this._size = size;
  63996. _this._multiRenderTargetOptions = {
  63997. samplingModes: samplingModes,
  63998. generateMipMaps: generateMipMaps,
  63999. generateDepthBuffer: generateDepthBuffer,
  64000. generateStencilBuffer: generateStencilBuffer,
  64001. generateDepthTexture: generateDepthTexture,
  64002. types: types,
  64003. textureCount: count
  64004. };
  64005. _this._createInternalTextures();
  64006. _this._createTextures();
  64007. return _this;
  64008. }
  64009. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64010. get: function () {
  64011. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64012. },
  64013. enumerable: true,
  64014. configurable: true
  64015. });
  64016. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64017. get: function () {
  64018. return this._textures;
  64019. },
  64020. enumerable: true,
  64021. configurable: true
  64022. });
  64023. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64024. get: function () {
  64025. return this._textures[this._textures.length - 1];
  64026. },
  64027. enumerable: true,
  64028. configurable: true
  64029. });
  64030. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64031. set: function (wrap) {
  64032. if (this._textures) {
  64033. for (var i = 0; i < this._textures.length; i++) {
  64034. this._textures[i].wrapU = wrap;
  64035. }
  64036. }
  64037. },
  64038. enumerable: true,
  64039. configurable: true
  64040. });
  64041. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64042. set: function (wrap) {
  64043. if (this._textures) {
  64044. for (var i = 0; i < this._textures.length; i++) {
  64045. this._textures[i].wrapV = wrap;
  64046. }
  64047. }
  64048. },
  64049. enumerable: true,
  64050. configurable: true
  64051. });
  64052. MultiRenderTarget.prototype._rebuild = function () {
  64053. this.releaseInternalTextures();
  64054. this._createInternalTextures();
  64055. for (var i = 0; i < this._internalTextures.length; i++) {
  64056. var texture = this._textures[i];
  64057. texture._texture = this._internalTextures[i];
  64058. }
  64059. // Keeps references to frame buffer and stencil/depth buffer
  64060. this._texture = this._internalTextures[0];
  64061. };
  64062. MultiRenderTarget.prototype._createInternalTextures = function () {
  64063. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64064. };
  64065. MultiRenderTarget.prototype._createTextures = function () {
  64066. this._textures = [];
  64067. for (var i = 0; i < this._internalTextures.length; i++) {
  64068. var texture = new BABYLON.Texture(null, this.getScene());
  64069. texture._texture = this._internalTextures[i];
  64070. this._textures.push(texture);
  64071. }
  64072. // Keeps references to frame buffer and stencil/depth buffer
  64073. this._texture = this._internalTextures[0];
  64074. };
  64075. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64076. get: function () {
  64077. return this._samples;
  64078. },
  64079. set: function (value) {
  64080. if (this._samples === value) {
  64081. return;
  64082. }
  64083. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64084. },
  64085. enumerable: true,
  64086. configurable: true
  64087. });
  64088. MultiRenderTarget.prototype.resize = function (size) {
  64089. this.releaseInternalTextures();
  64090. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64091. this._createInternalTextures();
  64092. };
  64093. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64094. var _this = this;
  64095. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64096. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64097. });
  64098. };
  64099. MultiRenderTarget.prototype.dispose = function () {
  64100. this.releaseInternalTextures();
  64101. _super.prototype.dispose.call(this);
  64102. };
  64103. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64104. if (!this._internalTextures) {
  64105. return;
  64106. }
  64107. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64108. if (this._internalTextures[i] !== undefined) {
  64109. this._internalTextures[i].dispose();
  64110. this._internalTextures.splice(i, 1);
  64111. }
  64112. }
  64113. };
  64114. return MultiRenderTarget;
  64115. }(BABYLON.RenderTargetTexture));
  64116. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64117. })(BABYLON || (BABYLON = {}));
  64118. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64119. var BABYLON;
  64120. (function (BABYLON) {
  64121. var MirrorTexture = /** @class */ (function (_super) {
  64122. __extends(MirrorTexture, _super);
  64123. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64124. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64126. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64127. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64128. _this.scene = scene;
  64129. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64130. _this._transformMatrix = BABYLON.Matrix.Zero();
  64131. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64132. _this._adaptiveBlurKernel = 0;
  64133. _this._blurKernelX = 0;
  64134. _this._blurKernelY = 0;
  64135. _this._blurRatio = 1.0;
  64136. _this.ignoreCameraViewport = true;
  64137. _this._updateGammaSpace();
  64138. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64139. _this._updateGammaSpace;
  64140. });
  64141. _this.onBeforeRenderObservable.add(function () {
  64142. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64143. _this._savedViewMatrix = scene.getViewMatrix();
  64144. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64145. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64146. scene.clipPlane = _this.mirrorPlane;
  64147. scene.getEngine().cullBackFaces = false;
  64148. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64149. });
  64150. _this.onAfterRenderObservable.add(function () {
  64151. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64152. scene.getEngine().cullBackFaces = true;
  64153. scene._mirroredCameraPosition = null;
  64154. delete scene.clipPlane;
  64155. });
  64156. return _this;
  64157. }
  64158. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64159. get: function () {
  64160. return this._blurRatio;
  64161. },
  64162. set: function (value) {
  64163. if (this._blurRatio === value) {
  64164. return;
  64165. }
  64166. this._blurRatio = value;
  64167. this._preparePostProcesses();
  64168. },
  64169. enumerable: true,
  64170. configurable: true
  64171. });
  64172. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64173. set: function (value) {
  64174. this._adaptiveBlurKernel = value;
  64175. this._autoComputeBlurKernel();
  64176. },
  64177. enumerable: true,
  64178. configurable: true
  64179. });
  64180. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64181. set: function (value) {
  64182. this.blurKernelX = value;
  64183. this.blurKernelY = value;
  64184. },
  64185. enumerable: true,
  64186. configurable: true
  64187. });
  64188. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64189. get: function () {
  64190. return this._blurKernelX;
  64191. },
  64192. set: function (value) {
  64193. if (this._blurKernelX === value) {
  64194. return;
  64195. }
  64196. this._blurKernelX = value;
  64197. this._preparePostProcesses();
  64198. },
  64199. enumerable: true,
  64200. configurable: true
  64201. });
  64202. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64203. get: function () {
  64204. return this._blurKernelY;
  64205. },
  64206. set: function (value) {
  64207. if (this._blurKernelY === value) {
  64208. return;
  64209. }
  64210. this._blurKernelY = value;
  64211. this._preparePostProcesses();
  64212. },
  64213. enumerable: true,
  64214. configurable: true
  64215. });
  64216. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64217. var engine = this.getScene().getEngine();
  64218. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64219. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64220. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64221. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64222. };
  64223. MirrorTexture.prototype._onRatioRescale = function () {
  64224. if (this._sizeRatio) {
  64225. this.resize(this._initialSizeParameter);
  64226. if (!this._adaptiveBlurKernel) {
  64227. this._preparePostProcesses();
  64228. }
  64229. }
  64230. if (this._adaptiveBlurKernel) {
  64231. this._autoComputeBlurKernel();
  64232. }
  64233. };
  64234. MirrorTexture.prototype._updateGammaSpace = function () {
  64235. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64236. };
  64237. MirrorTexture.prototype._preparePostProcesses = function () {
  64238. this.clearPostProcesses(true);
  64239. if (this._blurKernelX && this._blurKernelY) {
  64240. var engine = this.getScene().getEngine();
  64241. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64242. 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);
  64243. this._blurX.autoClear = false;
  64244. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64245. this._blurX.inputTexture = this._texture;
  64246. }
  64247. else {
  64248. this._blurX.alwaysForcePOT = true;
  64249. }
  64250. 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);
  64251. this._blurY.autoClear = false;
  64252. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64253. this.addPostProcess(this._blurX);
  64254. this.addPostProcess(this._blurY);
  64255. }
  64256. else {
  64257. if (this._blurY) {
  64258. this.removePostProcess(this._blurY);
  64259. this._blurY.dispose();
  64260. this._blurY = null;
  64261. }
  64262. if (this._blurX) {
  64263. this.removePostProcess(this._blurX);
  64264. this._blurX.dispose();
  64265. this._blurX = null;
  64266. }
  64267. }
  64268. };
  64269. MirrorTexture.prototype.clone = function () {
  64270. var scene = this.getScene();
  64271. if (!scene) {
  64272. return this;
  64273. }
  64274. var textureSize = this.getSize();
  64275. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64276. // Base texture
  64277. newTexture.hasAlpha = this.hasAlpha;
  64278. newTexture.level = this.level;
  64279. // Mirror Texture
  64280. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64281. if (this.renderList) {
  64282. newTexture.renderList = this.renderList.slice(0);
  64283. }
  64284. return newTexture;
  64285. };
  64286. MirrorTexture.prototype.serialize = function () {
  64287. if (!this.name) {
  64288. return null;
  64289. }
  64290. var serializationObject = _super.prototype.serialize.call(this);
  64291. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64292. return serializationObject;
  64293. };
  64294. MirrorTexture.prototype.dispose = function () {
  64295. _super.prototype.dispose.call(this);
  64296. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64297. };
  64298. return MirrorTexture;
  64299. }(BABYLON.RenderTargetTexture));
  64300. BABYLON.MirrorTexture = MirrorTexture;
  64301. })(BABYLON || (BABYLON = {}));
  64302. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64303. var BABYLON;
  64304. (function (BABYLON) {
  64305. /**
  64306. * Creates a refraction texture used by refraction channel of the standard material.
  64307. * @param name the texture name
  64308. * @param size size of the underlying texture
  64309. * @param scene root scene
  64310. */
  64311. var RefractionTexture = /** @class */ (function (_super) {
  64312. __extends(RefractionTexture, _super);
  64313. function RefractionTexture(name, size, scene, generateMipMaps) {
  64314. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64315. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64316. _this.depth = 2.0;
  64317. _this.onBeforeRenderObservable.add(function () {
  64318. scene.clipPlane = _this.refractionPlane;
  64319. });
  64320. _this.onAfterRenderObservable.add(function () {
  64321. delete scene.clipPlane;
  64322. });
  64323. return _this;
  64324. }
  64325. RefractionTexture.prototype.clone = function () {
  64326. var scene = this.getScene();
  64327. if (!scene) {
  64328. return this;
  64329. }
  64330. var textureSize = this.getSize();
  64331. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64332. // Base texture
  64333. newTexture.hasAlpha = this.hasAlpha;
  64334. newTexture.level = this.level;
  64335. // Refraction Texture
  64336. newTexture.refractionPlane = this.refractionPlane.clone();
  64337. if (this.renderList) {
  64338. newTexture.renderList = this.renderList.slice(0);
  64339. }
  64340. newTexture.depth = this.depth;
  64341. return newTexture;
  64342. };
  64343. RefractionTexture.prototype.serialize = function () {
  64344. if (!this.name) {
  64345. return null;
  64346. }
  64347. var serializationObject = _super.prototype.serialize.call(this);
  64348. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64349. serializationObject.depth = this.depth;
  64350. return serializationObject;
  64351. };
  64352. return RefractionTexture;
  64353. }(BABYLON.RenderTargetTexture));
  64354. BABYLON.RefractionTexture = RefractionTexture;
  64355. })(BABYLON || (BABYLON = {}));
  64356. //# sourceMappingURL=babylon.refractionTexture.js.map
  64357. var BABYLON;
  64358. (function (BABYLON) {
  64359. /**
  64360. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64361. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64362. */
  64363. var DynamicTexture = /** @class */ (function (_super) {
  64364. __extends(DynamicTexture, _super);
  64365. /**
  64366. * Creates a {BABYLON.DynamicTexture}
  64367. * @param name defines the name of the texture
  64368. * @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
  64369. * @param scene defines the scene where you want the texture
  64370. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64371. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64372. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64373. */
  64374. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64375. if (scene === void 0) { scene = null; }
  64376. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64377. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64378. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64379. _this.name = name;
  64380. _this._engine = _this.getScene().getEngine();
  64381. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64382. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64383. _this._generateMipMaps = generateMipMaps;
  64384. if (options.getContext) {
  64385. _this._canvas = options;
  64386. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64387. }
  64388. else {
  64389. _this._canvas = document.createElement("canvas");
  64390. if (options.width || options.width === 0) {
  64391. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64392. }
  64393. else {
  64394. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64395. }
  64396. }
  64397. var textureSize = _this.getSize();
  64398. _this._canvas.width = textureSize.width;
  64399. _this._canvas.height = textureSize.height;
  64400. _this._context = _this._canvas.getContext("2d");
  64401. return _this;
  64402. }
  64403. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64404. /**
  64405. * Gets the current state of canRescale
  64406. */
  64407. get: function () {
  64408. return true;
  64409. },
  64410. enumerable: true,
  64411. configurable: true
  64412. });
  64413. DynamicTexture.prototype._recreate = function (textureSize) {
  64414. this._canvas.width = textureSize.width;
  64415. this._canvas.height = textureSize.height;
  64416. this.releaseInternalTexture();
  64417. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64418. };
  64419. /**
  64420. * Scales the texture
  64421. * @param ratio the scale factor to apply to both width and height
  64422. */
  64423. DynamicTexture.prototype.scale = function (ratio) {
  64424. var textureSize = this.getSize();
  64425. textureSize.width *= ratio;
  64426. textureSize.height *= ratio;
  64427. this._recreate(textureSize);
  64428. };
  64429. /**
  64430. * Resizes the texture
  64431. * @param width the new width
  64432. * @param height the new height
  64433. */
  64434. DynamicTexture.prototype.scaleTo = function (width, height) {
  64435. var textureSize = this.getSize();
  64436. textureSize.width = width;
  64437. textureSize.height = height;
  64438. this._recreate(textureSize);
  64439. };
  64440. /**
  64441. * Gets the context of the canvas used by the texture
  64442. * @returns the canvas context of the dynamic texture
  64443. */
  64444. DynamicTexture.prototype.getContext = function () {
  64445. return this._context;
  64446. };
  64447. /**
  64448. * Clears the texture
  64449. */
  64450. DynamicTexture.prototype.clear = function () {
  64451. var size = this.getSize();
  64452. this._context.fillRect(0, 0, size.width, size.height);
  64453. };
  64454. /**
  64455. * Updates the texture
  64456. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64457. */
  64458. DynamicTexture.prototype.update = function (invertY) {
  64459. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64460. };
  64461. /**
  64462. * Draws text onto the texture
  64463. * @param text defines the text to be drawn
  64464. * @param x defines the placement of the text from the left
  64465. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64466. * @param font defines the font to be used with font-style, font-size, font-name
  64467. * @param color defines the color used for the text
  64468. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64469. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64470. * @param update defines whether texture is immediately update (default is true)
  64471. */
  64472. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64473. if (update === void 0) { update = true; }
  64474. var size = this.getSize();
  64475. if (clearColor) {
  64476. this._context.fillStyle = clearColor;
  64477. this._context.fillRect(0, 0, size.width, size.height);
  64478. }
  64479. this._context.font = font;
  64480. if (x === null || x === undefined) {
  64481. var textSize = this._context.measureText(text);
  64482. x = (size.width - textSize.width) / 2;
  64483. }
  64484. if (y === null || y === undefined) {
  64485. var fontSize = parseInt((font.replace(/\D/g, '')));
  64486. y = (size.height / 2) + (fontSize / 3.65);
  64487. }
  64488. this._context.fillStyle = color;
  64489. this._context.fillText(text, x, y);
  64490. if (update) {
  64491. this.update(invertY);
  64492. }
  64493. };
  64494. /**
  64495. * Clones the texture
  64496. * @returns the clone of the texture.
  64497. */
  64498. DynamicTexture.prototype.clone = function () {
  64499. var scene = this.getScene();
  64500. if (!scene) {
  64501. return this;
  64502. }
  64503. var textureSize = this.getSize();
  64504. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64505. // Base texture
  64506. newTexture.hasAlpha = this.hasAlpha;
  64507. newTexture.level = this.level;
  64508. // Dynamic Texture
  64509. newTexture.wrapU = this.wrapU;
  64510. newTexture.wrapV = this.wrapV;
  64511. return newTexture;
  64512. };
  64513. /** @hidden */
  64514. DynamicTexture.prototype._rebuild = function () {
  64515. this.update();
  64516. };
  64517. return DynamicTexture;
  64518. }(BABYLON.Texture));
  64519. BABYLON.DynamicTexture = DynamicTexture;
  64520. })(BABYLON || (BABYLON = {}));
  64521. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64522. var BABYLON;
  64523. (function (BABYLON) {
  64524. var VideoTexture = /** @class */ (function (_super) {
  64525. __extends(VideoTexture, _super);
  64526. /**
  64527. * Creates a video texture.
  64528. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64529. * @param {string | null} name optional name, will detect from video source, if not defined
  64530. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64531. * @param {BABYLON.Scene} scene is obviously the current scene.
  64532. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64533. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64534. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64535. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64536. */
  64537. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64538. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64539. if (invertY === void 0) { invertY = false; }
  64540. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64541. if (settings === void 0) { settings = {
  64542. autoPlay: true,
  64543. loop: true,
  64544. autoUpdateTexture: true,
  64545. }; }
  64546. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64547. _this._stillImageCaptured = false;
  64548. _this._createInternalTexture = function () {
  64549. if (_this._texture != null) {
  64550. return;
  64551. }
  64552. if (!_this._engine.needPOTTextures ||
  64553. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64554. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64555. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64556. }
  64557. else {
  64558. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64559. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64560. _this._generateMipMaps = false;
  64561. }
  64562. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64563. if (!_this.video.autoplay) {
  64564. var oldHandler_1 = _this.video.onplaying;
  64565. _this.video.onplaying = function () {
  64566. _this.video.onplaying = oldHandler_1;
  64567. _this._texture.isReady = true;
  64568. _this._updateInternalTexture();
  64569. _this.video.pause();
  64570. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64571. _this.onLoadObservable.notifyObservers(_this);
  64572. }
  64573. };
  64574. _this.video.play();
  64575. }
  64576. else {
  64577. _this._texture.isReady = true;
  64578. _this._updateInternalTexture();
  64579. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64580. _this.onLoadObservable.notifyObservers(_this);
  64581. }
  64582. }
  64583. };
  64584. _this.reset = function () {
  64585. if (_this._texture == null) {
  64586. return;
  64587. }
  64588. _this._texture.dispose();
  64589. _this._texture = null;
  64590. };
  64591. _this._updateInternalTexture = function (e) {
  64592. if (_this._texture == null || !_this._texture.isReady) {
  64593. return;
  64594. }
  64595. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64596. return;
  64597. }
  64598. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64599. };
  64600. _this._engine = _this.getScene().getEngine();
  64601. _this._generateMipMaps = generateMipMaps;
  64602. _this._samplingMode = samplingMode;
  64603. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64604. _this.name = name || _this._getName(src);
  64605. _this.video = _this._getVideo(src);
  64606. if (settings.autoPlay !== undefined) {
  64607. _this.video.autoplay = settings.autoPlay;
  64608. }
  64609. if (settings.loop !== undefined) {
  64610. _this.video.loop = settings.loop;
  64611. }
  64612. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64613. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64614. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64615. _this.video.addEventListener("emptied", _this.reset);
  64616. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64617. _this._createInternalTexture();
  64618. }
  64619. return _this;
  64620. }
  64621. VideoTexture.prototype._getName = function (src) {
  64622. if (src instanceof HTMLVideoElement) {
  64623. return src.currentSrc;
  64624. }
  64625. if (typeof src === "object") {
  64626. return src.toString();
  64627. }
  64628. return src;
  64629. };
  64630. ;
  64631. VideoTexture.prototype._getVideo = function (src) {
  64632. if (src instanceof HTMLVideoElement) {
  64633. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64634. return src;
  64635. }
  64636. var video = document.createElement("video");
  64637. if (typeof src === "string") {
  64638. BABYLON.Tools.SetCorsBehavior(src, video);
  64639. video.src = src;
  64640. }
  64641. else {
  64642. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64643. src.forEach(function (url) {
  64644. var source = document.createElement("source");
  64645. source.src = url;
  64646. video.appendChild(source);
  64647. });
  64648. }
  64649. return video;
  64650. };
  64651. ;
  64652. /**
  64653. * Internal method to initiate `update`.
  64654. */
  64655. VideoTexture.prototype._rebuild = function () {
  64656. this.update();
  64657. };
  64658. /**
  64659. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64660. */
  64661. VideoTexture.prototype.update = function () {
  64662. if (!this.autoUpdateTexture) {
  64663. // Expecting user to call `updateTexture` manually
  64664. return;
  64665. }
  64666. this.updateTexture(true);
  64667. };
  64668. /**
  64669. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64670. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64671. */
  64672. VideoTexture.prototype.updateTexture = function (isVisible) {
  64673. if (!isVisible) {
  64674. return;
  64675. }
  64676. if (this.video.paused && this._stillImageCaptured) {
  64677. return;
  64678. }
  64679. this._stillImageCaptured = true;
  64680. this._updateInternalTexture();
  64681. };
  64682. /**
  64683. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64684. * @param url New url.
  64685. */
  64686. VideoTexture.prototype.updateURL = function (url) {
  64687. this.video.src = url;
  64688. };
  64689. VideoTexture.prototype.dispose = function () {
  64690. _super.prototype.dispose.call(this);
  64691. this.video.removeEventListener("canplay", this._createInternalTexture);
  64692. this.video.removeEventListener("paused", this._updateInternalTexture);
  64693. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64694. this.video.removeEventListener("emptied", this.reset);
  64695. this.video.pause();
  64696. };
  64697. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64698. var video = document.createElement("video");
  64699. var constraintsDeviceId;
  64700. if (constraints && constraints.deviceId) {
  64701. constraintsDeviceId = {
  64702. exact: constraints.deviceId,
  64703. };
  64704. }
  64705. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64706. if (navigator.mediaDevices) {
  64707. navigator.mediaDevices.getUserMedia({ video: constraints })
  64708. .then(function (stream) {
  64709. if (video.mozSrcObject !== undefined) {
  64710. // hack for Firefox < 19
  64711. video.mozSrcObject = stream;
  64712. }
  64713. else {
  64714. video.srcObject = stream;
  64715. }
  64716. var onPlaying = function () {
  64717. if (onReady) {
  64718. onReady(new VideoTexture("video", video, scene, true, true));
  64719. }
  64720. video.removeEventListener("playing", onPlaying);
  64721. };
  64722. video.addEventListener("playing", onPlaying);
  64723. video.play();
  64724. })
  64725. .catch(function (err) {
  64726. BABYLON.Tools.Error(err.name);
  64727. });
  64728. }
  64729. else {
  64730. navigator.getUserMedia =
  64731. navigator.getUserMedia ||
  64732. navigator.webkitGetUserMedia ||
  64733. navigator.mozGetUserMedia ||
  64734. navigator.msGetUserMedia;
  64735. if (navigator.getUserMedia) {
  64736. navigator.getUserMedia({
  64737. video: {
  64738. deviceId: constraintsDeviceId,
  64739. width: {
  64740. min: (constraints && constraints.minWidth) || 256,
  64741. max: (constraints && constraints.maxWidth) || 640,
  64742. },
  64743. height: {
  64744. min: (constraints && constraints.minHeight) || 256,
  64745. max: (constraints && constraints.maxHeight) || 480,
  64746. },
  64747. },
  64748. }, function (stream) {
  64749. if (video.mozSrcObject !== undefined) {
  64750. // hack for Firefox < 19
  64751. video.mozSrcObject = stream;
  64752. }
  64753. else {
  64754. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64755. }
  64756. video.play();
  64757. if (onReady) {
  64758. onReady(new VideoTexture("video", video, scene, true, true));
  64759. }
  64760. }, function (e) {
  64761. BABYLON.Tools.Error(e.name);
  64762. });
  64763. }
  64764. }
  64765. };
  64766. return VideoTexture;
  64767. }(BABYLON.Texture));
  64768. BABYLON.VideoTexture = VideoTexture;
  64769. })(BABYLON || (BABYLON = {}));
  64770. //# sourceMappingURL=babylon.videoTexture.js.map
  64771. var BABYLON;
  64772. (function (BABYLON) {
  64773. var RawTexture = /** @class */ (function (_super) {
  64774. __extends(RawTexture, _super);
  64775. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64777. if (invertY === void 0) { invertY = false; }
  64778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64779. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64780. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64781. _this.format = format;
  64782. _this._engine = scene.getEngine();
  64783. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64784. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64785. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64786. return _this;
  64787. }
  64788. RawTexture.prototype.update = function (data) {
  64789. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64790. };
  64791. // Statics
  64792. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64793. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64794. if (invertY === void 0) { invertY = false; }
  64795. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64796. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64797. };
  64798. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64799. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64800. if (invertY === void 0) { invertY = false; }
  64801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64802. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64803. };
  64804. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64805. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64806. if (invertY === void 0) { invertY = false; }
  64807. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64808. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64809. };
  64810. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64811. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64812. if (invertY === void 0) { invertY = false; }
  64813. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64814. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64815. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64816. };
  64817. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64818. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64819. if (invertY === void 0) { invertY = false; }
  64820. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64821. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64822. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64823. };
  64824. return RawTexture;
  64825. }(BABYLON.Texture));
  64826. BABYLON.RawTexture = RawTexture;
  64827. })(BABYLON || (BABYLON = {}));
  64828. //# sourceMappingURL=babylon.rawTexture.js.map
  64829. var BABYLON;
  64830. (function (BABYLON) {
  64831. /**
  64832. * Class used to store 3D textures containing user data
  64833. */
  64834. var RawTexture3D = /** @class */ (function (_super) {
  64835. __extends(RawTexture3D, _super);
  64836. /**
  64837. * Create a new RawTexture3D
  64838. * @param data defines the data of the texture
  64839. * @param width defines the width of the texture
  64840. * @param height defines the height of the texture
  64841. * @param depth defines the depth of the texture
  64842. * @param format defines the texture format to use
  64843. * @param scene defines the hosting scene
  64844. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64845. * @param invertY defines if texture must be stored with Y axis inverted
  64846. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64847. */
  64848. function RawTexture3D(data, width, height, depth,
  64849. /** Gets or sets the texture format to use*/
  64850. format, scene, generateMipMaps, invertY, samplingMode) {
  64851. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64852. if (invertY === void 0) { invertY = false; }
  64853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64854. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64855. _this.format = format;
  64856. _this._engine = scene.getEngine();
  64857. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64858. _this.is3D = true;
  64859. return _this;
  64860. }
  64861. /**
  64862. * Update the texture with new data
  64863. * @param data defines the data to store in the texture
  64864. */
  64865. RawTexture3D.prototype.update = function (data) {
  64866. if (!this._texture) {
  64867. return;
  64868. }
  64869. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64870. };
  64871. return RawTexture3D;
  64872. }(BABYLON.Texture));
  64873. BABYLON.RawTexture3D = RawTexture3D;
  64874. })(BABYLON || (BABYLON = {}));
  64875. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64876. var BABYLON;
  64877. (function (BABYLON) {
  64878. /**
  64879. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64880. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64881. */
  64882. var PostProcess = /** @class */ (function () {
  64883. /**
  64884. * Creates a new instance PostProcess
  64885. * @param name The name of the PostProcess.
  64886. * @param fragmentUrl The url of the fragment shader to be used.
  64887. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64888. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64889. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64890. * @param camera The camera to apply the render pass to.
  64891. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64892. * @param engine The engine which the post process will be applied. (default: current engine)
  64893. * @param reusable If the post process can be reused on the same frame. (default: false)
  64894. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64895. * @param textureType Type of textures used when performing the post process. (default: 0)
  64896. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64897. * @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
  64898. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64899. */
  64900. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64901. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64902. if (defines === void 0) { defines = null; }
  64903. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64904. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64905. if (blockCompilation === void 0) { blockCompilation = false; }
  64906. this.name = name;
  64907. /**
  64908. * Width of the texture to apply the post process on
  64909. */
  64910. this.width = -1;
  64911. /**
  64912. * Height of the texture to apply the post process on
  64913. */
  64914. this.height = -1;
  64915. /**
  64916. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64917. */
  64918. this._outputTexture = null;
  64919. /**
  64920. * If the buffer needs to be cleared before applying the post process. (default: true)
  64921. * Should be set to false if shader will overwrite all previous pixels.
  64922. */
  64923. this.autoClear = true;
  64924. /**
  64925. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64926. */
  64927. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64928. /**
  64929. * Animations to be used for the post processing
  64930. */
  64931. this.animations = new Array();
  64932. /**
  64933. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64934. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64935. */
  64936. this.enablePixelPerfectMode = false;
  64937. /**
  64938. * Force the postprocess to be applied without taking in account viewport
  64939. */
  64940. this.forceFullscreenViewport = true;
  64941. /**
  64942. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64943. */
  64944. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64945. /**
  64946. * Force textures to be a power of two (default: false)
  64947. */
  64948. this.alwaysForcePOT = false;
  64949. /**
  64950. * Number of sample textures (default: 1)
  64951. */
  64952. this.samples = 1;
  64953. /**
  64954. * Modify the scale of the post process to be the same as the viewport (default: false)
  64955. */
  64956. this.adaptScaleToCurrentViewport = false;
  64957. this._reusable = false;
  64958. /**
  64959. * Smart array of input and output textures for the post process.
  64960. */
  64961. this._textures = new BABYLON.SmartArray(2);
  64962. /**
  64963. * The index in _textures that corresponds to the output texture.
  64964. */
  64965. this._currentRenderTextureInd = 0;
  64966. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64967. this._texelSize = BABYLON.Vector2.Zero();
  64968. // Events
  64969. /**
  64970. * An event triggered when the postprocess is activated.
  64971. */
  64972. this.onActivateObservable = new BABYLON.Observable();
  64973. /**
  64974. * An event triggered when the postprocess changes its size.
  64975. */
  64976. this.onSizeChangedObservable = new BABYLON.Observable();
  64977. /**
  64978. * An event triggered when the postprocess applies its effect.
  64979. */
  64980. this.onApplyObservable = new BABYLON.Observable();
  64981. /**
  64982. * An event triggered before rendering the postprocess
  64983. */
  64984. this.onBeforeRenderObservable = new BABYLON.Observable();
  64985. /**
  64986. * An event triggered after rendering the postprocess
  64987. */
  64988. this.onAfterRenderObservable = new BABYLON.Observable();
  64989. if (camera != null) {
  64990. this._camera = camera;
  64991. this._scene = camera.getScene();
  64992. camera.attachPostProcess(this);
  64993. this._engine = this._scene.getEngine();
  64994. this._scene.postProcesses.push(this);
  64995. }
  64996. else if (engine) {
  64997. this._engine = engine;
  64998. this._engine.postProcesses.push(this);
  64999. }
  65000. this._options = options;
  65001. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65002. this._reusable = reusable || false;
  65003. this._textureType = textureType;
  65004. this._samplers = samplers || [];
  65005. this._samplers.push("textureSampler");
  65006. this._fragmentUrl = fragmentUrl;
  65007. this._vertexUrl = vertexUrl;
  65008. this._parameters = parameters || [];
  65009. this._parameters.push("scale");
  65010. this._indexParameters = indexParameters;
  65011. if (!blockCompilation) {
  65012. this.updateEffect(defines);
  65013. }
  65014. }
  65015. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65016. /**
  65017. * A function that is added to the onActivateObservable
  65018. */
  65019. set: function (callback) {
  65020. if (this._onActivateObserver) {
  65021. this.onActivateObservable.remove(this._onActivateObserver);
  65022. }
  65023. if (callback) {
  65024. this._onActivateObserver = this.onActivateObservable.add(callback);
  65025. }
  65026. },
  65027. enumerable: true,
  65028. configurable: true
  65029. });
  65030. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65031. /**
  65032. * A function that is added to the onSizeChangedObservable
  65033. */
  65034. set: function (callback) {
  65035. if (this._onSizeChangedObserver) {
  65036. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65037. }
  65038. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65039. },
  65040. enumerable: true,
  65041. configurable: true
  65042. });
  65043. Object.defineProperty(PostProcess.prototype, "onApply", {
  65044. /**
  65045. * A function that is added to the onApplyObservable
  65046. */
  65047. set: function (callback) {
  65048. if (this._onApplyObserver) {
  65049. this.onApplyObservable.remove(this._onApplyObserver);
  65050. }
  65051. this._onApplyObserver = this.onApplyObservable.add(callback);
  65052. },
  65053. enumerable: true,
  65054. configurable: true
  65055. });
  65056. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65057. /**
  65058. * A function that is added to the onBeforeRenderObservable
  65059. */
  65060. set: function (callback) {
  65061. if (this._onBeforeRenderObserver) {
  65062. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65063. }
  65064. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65065. },
  65066. enumerable: true,
  65067. configurable: true
  65068. });
  65069. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65070. /**
  65071. * A function that is added to the onAfterRenderObservable
  65072. */
  65073. set: function (callback) {
  65074. if (this._onAfterRenderObserver) {
  65075. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65076. }
  65077. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65078. },
  65079. enumerable: true,
  65080. configurable: true
  65081. });
  65082. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65083. /**
  65084. * 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
  65085. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65086. */
  65087. get: function () {
  65088. return this._textures.data[this._currentRenderTextureInd];
  65089. },
  65090. set: function (value) {
  65091. this._forcedOutputTexture = value;
  65092. },
  65093. enumerable: true,
  65094. configurable: true
  65095. });
  65096. /**
  65097. * Gets the camera which post process is applied to.
  65098. * @returns The camera the post process is applied to.
  65099. */
  65100. PostProcess.prototype.getCamera = function () {
  65101. return this._camera;
  65102. };
  65103. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65104. /**
  65105. * Gets the texel size of the postprocess.
  65106. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65107. */
  65108. get: function () {
  65109. if (this._shareOutputWithPostProcess) {
  65110. return this._shareOutputWithPostProcess.texelSize;
  65111. }
  65112. if (this._forcedOutputTexture) {
  65113. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65114. }
  65115. return this._texelSize;
  65116. },
  65117. enumerable: true,
  65118. configurable: true
  65119. });
  65120. /**
  65121. * Gets the engine which this post process belongs to.
  65122. * @returns The engine the post process was enabled with.
  65123. */
  65124. PostProcess.prototype.getEngine = function () {
  65125. return this._engine;
  65126. };
  65127. /**
  65128. * The effect that is created when initializing the post process.
  65129. * @returns The created effect corrisponding the the postprocess.
  65130. */
  65131. PostProcess.prototype.getEffect = function () {
  65132. return this._effect;
  65133. };
  65134. /**
  65135. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65136. * @param postProcess The post process to share the output with.
  65137. * @returns This post process.
  65138. */
  65139. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65140. this._disposeTextures();
  65141. this._shareOutputWithPostProcess = postProcess;
  65142. return this;
  65143. };
  65144. /**
  65145. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65146. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65147. */
  65148. PostProcess.prototype.useOwnOutput = function () {
  65149. if (this._textures.length == 0) {
  65150. this._textures = new BABYLON.SmartArray(2);
  65151. }
  65152. this._shareOutputWithPostProcess = null;
  65153. };
  65154. /**
  65155. * Updates the effect with the current post process compile time values and recompiles the shader.
  65156. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65157. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65158. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65159. * @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
  65160. * @param onCompiled Called when the shader has been compiled.
  65161. * @param onError Called if there is an error when compiling a shader.
  65162. */
  65163. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65164. if (defines === void 0) { defines = null; }
  65165. if (uniforms === void 0) { uniforms = null; }
  65166. if (samplers === void 0) { samplers = null; }
  65167. 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);
  65168. };
  65169. /**
  65170. * The post process is reusable if it can be used multiple times within one frame.
  65171. * @returns If the post process is reusable
  65172. */
  65173. PostProcess.prototype.isReusable = function () {
  65174. return this._reusable;
  65175. };
  65176. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65177. PostProcess.prototype.markTextureDirty = function () {
  65178. this.width = -1;
  65179. };
  65180. /**
  65181. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65182. * 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.
  65183. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65184. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65185. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65186. * @returns The target texture that was bound to be written to.
  65187. */
  65188. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65189. var _this = this;
  65190. if (sourceTexture === void 0) { sourceTexture = null; }
  65191. camera = camera || this._camera;
  65192. var scene = camera.getScene();
  65193. var engine = scene.getEngine();
  65194. var maxSize = engine.getCaps().maxTextureSize;
  65195. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65196. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65197. // 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
  65198. var webVRCamera = camera.parent;
  65199. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65200. requiredWidth /= 2;
  65201. }
  65202. var desiredWidth = (this._options.width || requiredWidth);
  65203. var desiredHeight = this._options.height || requiredHeight;
  65204. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65205. if (this.adaptScaleToCurrentViewport) {
  65206. var currentViewport = engine.currentViewport;
  65207. if (currentViewport) {
  65208. desiredWidth *= currentViewport.width;
  65209. desiredHeight *= currentViewport.height;
  65210. }
  65211. }
  65212. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65213. if (!this._options.width) {
  65214. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65215. }
  65216. if (!this._options.height) {
  65217. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65218. }
  65219. }
  65220. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65221. if (this._textures.length > 0) {
  65222. for (var i = 0; i < this._textures.length; i++) {
  65223. this._engine._releaseTexture(this._textures.data[i]);
  65224. }
  65225. this._textures.reset();
  65226. }
  65227. this.width = desiredWidth;
  65228. this.height = desiredHeight;
  65229. var textureSize = { width: this.width, height: this.height };
  65230. var textureOptions = {
  65231. generateMipMaps: false,
  65232. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65233. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65234. samplingMode: this.renderTargetSamplingMode,
  65235. type: this._textureType
  65236. };
  65237. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65238. if (this._reusable) {
  65239. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65240. }
  65241. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65242. this.onSizeChangedObservable.notifyObservers(this);
  65243. }
  65244. this._textures.forEach(function (texture) {
  65245. if (texture.samples !== _this.samples) {
  65246. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65247. }
  65248. });
  65249. }
  65250. var target;
  65251. if (this._shareOutputWithPostProcess) {
  65252. target = this._shareOutputWithPostProcess.inputTexture;
  65253. }
  65254. else if (this._forcedOutputTexture) {
  65255. target = this._forcedOutputTexture;
  65256. this.width = this._forcedOutputTexture.width;
  65257. this.height = this._forcedOutputTexture.height;
  65258. }
  65259. else {
  65260. target = this.inputTexture;
  65261. }
  65262. // Bind the input of this post process to be used as the output of the previous post process.
  65263. if (this.enablePixelPerfectMode) {
  65264. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65265. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65266. }
  65267. else {
  65268. this._scaleRatio.copyFromFloats(1, 1);
  65269. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65270. }
  65271. this.onActivateObservable.notifyObservers(camera);
  65272. // Clear
  65273. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65274. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65275. }
  65276. if (this._reusable) {
  65277. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65278. }
  65279. return target;
  65280. };
  65281. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65282. /**
  65283. * If the post process is supported.
  65284. */
  65285. get: function () {
  65286. return this._effect.isSupported;
  65287. },
  65288. enumerable: true,
  65289. configurable: true
  65290. });
  65291. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65292. /**
  65293. * The aspect ratio of the output texture.
  65294. */
  65295. get: function () {
  65296. if (this._shareOutputWithPostProcess) {
  65297. return this._shareOutputWithPostProcess.aspectRatio;
  65298. }
  65299. if (this._forcedOutputTexture) {
  65300. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65301. }
  65302. return this.width / this.height;
  65303. },
  65304. enumerable: true,
  65305. configurable: true
  65306. });
  65307. /**
  65308. * Get a value indicating if the post-process is ready to be used
  65309. * @returns true if the post-process is ready (shader is compiled)
  65310. */
  65311. PostProcess.prototype.isReady = function () {
  65312. return this._effect && this._effect.isReady();
  65313. };
  65314. /**
  65315. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65316. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65317. */
  65318. PostProcess.prototype.apply = function () {
  65319. // Check
  65320. if (!this._effect || !this._effect.isReady())
  65321. return null;
  65322. // States
  65323. this._engine.enableEffect(this._effect);
  65324. this._engine.setState(false);
  65325. this._engine.setDepthBuffer(false);
  65326. this._engine.setDepthWrite(false);
  65327. // Alpha
  65328. this._engine.setAlphaMode(this.alphaMode);
  65329. if (this.alphaConstants) {
  65330. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65331. }
  65332. // Bind the output texture of the preivous post process as the input to this post process.
  65333. var source;
  65334. if (this._shareOutputWithPostProcess) {
  65335. source = this._shareOutputWithPostProcess.inputTexture;
  65336. }
  65337. else if (this._forcedOutputTexture) {
  65338. source = this._forcedOutputTexture;
  65339. }
  65340. else {
  65341. source = this.inputTexture;
  65342. }
  65343. this._effect._bindTexture("textureSampler", source);
  65344. // Parameters
  65345. this._effect.setVector2("scale", this._scaleRatio);
  65346. this.onApplyObservable.notifyObservers(this._effect);
  65347. return this._effect;
  65348. };
  65349. PostProcess.prototype._disposeTextures = function () {
  65350. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65351. return;
  65352. }
  65353. if (this._textures.length > 0) {
  65354. for (var i = 0; i < this._textures.length; i++) {
  65355. this._engine._releaseTexture(this._textures.data[i]);
  65356. }
  65357. }
  65358. this._textures.dispose();
  65359. };
  65360. /**
  65361. * Disposes the post process.
  65362. * @param camera The camera to dispose the post process on.
  65363. */
  65364. PostProcess.prototype.dispose = function (camera) {
  65365. camera = camera || this._camera;
  65366. this._disposeTextures();
  65367. if (this._scene) {
  65368. var index_1 = this._scene.postProcesses.indexOf(this);
  65369. if (index_1 !== -1) {
  65370. this._scene.postProcesses.splice(index_1, 1);
  65371. }
  65372. }
  65373. else {
  65374. var index_2 = this._engine.postProcesses.indexOf(this);
  65375. if (index_2 !== -1) {
  65376. this._engine.postProcesses.splice(index_2, 1);
  65377. }
  65378. }
  65379. if (!camera) {
  65380. return;
  65381. }
  65382. camera.detachPostProcess(this);
  65383. var index = camera._postProcesses.indexOf(this);
  65384. if (index === 0 && camera._postProcesses.length > 0) {
  65385. var firstPostProcess = this._camera._getFirstPostProcess();
  65386. if (firstPostProcess) {
  65387. firstPostProcess.markTextureDirty();
  65388. }
  65389. }
  65390. this.onActivateObservable.clear();
  65391. this.onAfterRenderObservable.clear();
  65392. this.onApplyObservable.clear();
  65393. this.onBeforeRenderObservable.clear();
  65394. this.onSizeChangedObservable.clear();
  65395. };
  65396. return PostProcess;
  65397. }());
  65398. BABYLON.PostProcess = PostProcess;
  65399. })(BABYLON || (BABYLON = {}));
  65400. //# sourceMappingURL=babylon.postProcess.js.map
  65401. var BABYLON;
  65402. (function (BABYLON) {
  65403. var PassPostProcess = /** @class */ (function (_super) {
  65404. __extends(PassPostProcess, _super);
  65405. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65406. if (camera === void 0) { camera = null; }
  65407. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65408. if (blockCompilation === void 0) { blockCompilation = false; }
  65409. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65410. }
  65411. return PassPostProcess;
  65412. }(BABYLON.PostProcess));
  65413. BABYLON.PassPostProcess = PassPostProcess;
  65414. })(BABYLON || (BABYLON = {}));
  65415. //# sourceMappingURL=babylon.passPostProcess.js.map
  65416. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65417. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65418. s = arguments[i];
  65419. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65420. t[p] = s[p];
  65421. }
  65422. return t;
  65423. };
  65424. var BABYLON;
  65425. (function (BABYLON) {
  65426. /**
  65427. * Default implementation IShadowGenerator.
  65428. * This is the main object responsible of generating shadows in the framework.
  65429. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65430. */
  65431. var ShadowGenerator = /** @class */ (function () {
  65432. /**
  65433. * Creates a ShadowGenerator object.
  65434. * A ShadowGenerator is the required tool to use the shadows.
  65435. * Each light casting shadows needs to use its own ShadowGenerator.
  65436. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65437. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65438. * @param light The light object generating the shadows.
  65439. * @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.
  65440. */
  65441. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65442. this._bias = 0.00005;
  65443. this._normalBias = 0;
  65444. this._blurBoxOffset = 1;
  65445. this._blurScale = 2;
  65446. this._blurKernel = 1;
  65447. this._useKernelBlur = false;
  65448. this._filter = ShadowGenerator.FILTER_NONE;
  65449. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65450. this._contactHardeningLightSizeUVRatio = 0.1;
  65451. this._darkness = 0;
  65452. this._transparencyShadow = false;
  65453. /**
  65454. * Controls the extent to which the shadows fade out at the edge of the frustum
  65455. * Used only by directionals and spots
  65456. */
  65457. this.frustumEdgeFalloff = 0;
  65458. /**
  65459. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65460. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65461. * It might on the other hand introduce peter panning.
  65462. */
  65463. this.forceBackFacesOnly = false;
  65464. this._lightDirection = BABYLON.Vector3.Zero();
  65465. this._viewMatrix = BABYLON.Matrix.Zero();
  65466. this._projectionMatrix = BABYLON.Matrix.Zero();
  65467. this._transformMatrix = BABYLON.Matrix.Zero();
  65468. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65469. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65470. this._currentFaceIndex = 0;
  65471. this._currentFaceIndexCache = 0;
  65472. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65473. this._mapSize = mapSize;
  65474. this._light = light;
  65475. this._scene = light.getScene();
  65476. light._shadowGenerator = this;
  65477. // Texture type fallback from float to int if not supported.
  65478. var caps = this._scene.getEngine().getCaps();
  65479. if (!useFullFloatFirst) {
  65480. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65481. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65482. }
  65483. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65484. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65485. }
  65486. else {
  65487. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65488. }
  65489. }
  65490. else {
  65491. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65492. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65493. }
  65494. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65495. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65496. }
  65497. else {
  65498. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65499. }
  65500. }
  65501. this._initializeGenerator();
  65502. this._applyFilterValues();
  65503. }
  65504. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65505. /**
  65506. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65507. */
  65508. get: function () {
  65509. return this._bias;
  65510. },
  65511. /**
  65512. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65513. */
  65514. set: function (bias) {
  65515. this._bias = bias;
  65516. },
  65517. enumerable: true,
  65518. configurable: true
  65519. });
  65520. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65521. /**
  65522. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65523. */
  65524. get: function () {
  65525. return this._normalBias;
  65526. },
  65527. /**
  65528. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65529. */
  65530. set: function (normalBias) {
  65531. this._normalBias = normalBias;
  65532. },
  65533. enumerable: true,
  65534. configurable: true
  65535. });
  65536. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65537. /**
  65538. * Gets the blur box offset: offset applied during the blur pass.
  65539. * Only usefull if useKernelBlur = false
  65540. */
  65541. get: function () {
  65542. return this._blurBoxOffset;
  65543. },
  65544. /**
  65545. * Sets the blur box offset: offset applied during the blur pass.
  65546. * Only usefull if useKernelBlur = false
  65547. */
  65548. set: function (value) {
  65549. if (this._blurBoxOffset === value) {
  65550. return;
  65551. }
  65552. this._blurBoxOffset = value;
  65553. this._disposeBlurPostProcesses();
  65554. },
  65555. enumerable: true,
  65556. configurable: true
  65557. });
  65558. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65559. /**
  65560. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65561. * 2 means half of the size.
  65562. */
  65563. get: function () {
  65564. return this._blurScale;
  65565. },
  65566. /**
  65567. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65568. * 2 means half of the size.
  65569. */
  65570. set: function (value) {
  65571. if (this._blurScale === value) {
  65572. return;
  65573. }
  65574. this._blurScale = value;
  65575. this._disposeBlurPostProcesses();
  65576. },
  65577. enumerable: true,
  65578. configurable: true
  65579. });
  65580. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65581. /**
  65582. * Gets the blur kernel: kernel size of the blur pass.
  65583. * Only usefull if useKernelBlur = true
  65584. */
  65585. get: function () {
  65586. return this._blurKernel;
  65587. },
  65588. /**
  65589. * Sets the blur kernel: kernel size of the blur pass.
  65590. * Only usefull if useKernelBlur = true
  65591. */
  65592. set: function (value) {
  65593. if (this._blurKernel === value) {
  65594. return;
  65595. }
  65596. this._blurKernel = value;
  65597. this._disposeBlurPostProcesses();
  65598. },
  65599. enumerable: true,
  65600. configurable: true
  65601. });
  65602. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65603. /**
  65604. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65605. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65606. */
  65607. get: function () {
  65608. return this._useKernelBlur;
  65609. },
  65610. /**
  65611. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65612. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65613. */
  65614. set: function (value) {
  65615. if (this._useKernelBlur === value) {
  65616. return;
  65617. }
  65618. this._useKernelBlur = value;
  65619. this._disposeBlurPostProcesses();
  65620. },
  65621. enumerable: true,
  65622. configurable: true
  65623. });
  65624. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65625. /**
  65626. * Gets the depth scale used in ESM mode.
  65627. */
  65628. get: function () {
  65629. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65630. },
  65631. /**
  65632. * Sets the depth scale used in ESM mode.
  65633. * This can override the scale stored on the light.
  65634. */
  65635. set: function (value) {
  65636. this._depthScale = value;
  65637. },
  65638. enumerable: true,
  65639. configurable: true
  65640. });
  65641. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65642. /**
  65643. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65644. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65645. */
  65646. get: function () {
  65647. return this._filter;
  65648. },
  65649. /**
  65650. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65651. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65652. */
  65653. set: function (value) {
  65654. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65655. if (this._light.needCube()) {
  65656. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65657. this.useExponentialShadowMap = true;
  65658. return;
  65659. }
  65660. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65661. this.useCloseExponentialShadowMap = true;
  65662. return;
  65663. }
  65664. // PCF on cubemap would also be expensive
  65665. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65666. this.usePoissonSampling = true;
  65667. return;
  65668. }
  65669. }
  65670. // Weblg1 fallback for PCF.
  65671. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65672. if (this._scene.getEngine().webGLVersion === 1) {
  65673. this.usePoissonSampling = true;
  65674. return;
  65675. }
  65676. }
  65677. if (this._filter === value) {
  65678. return;
  65679. }
  65680. this._filter = value;
  65681. this._disposeBlurPostProcesses();
  65682. this._applyFilterValues();
  65683. this._light._markMeshesAsLightDirty();
  65684. },
  65685. enumerable: true,
  65686. configurable: true
  65687. });
  65688. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65689. /**
  65690. * Gets if the current filter is set to Poisson Sampling.
  65691. */
  65692. get: function () {
  65693. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65694. },
  65695. /**
  65696. * Sets the current filter to Poisson Sampling.
  65697. */
  65698. set: function (value) {
  65699. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65700. return;
  65701. }
  65702. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65703. },
  65704. enumerable: true,
  65705. configurable: true
  65706. });
  65707. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65708. /**
  65709. * Gets if the current filter is set to VSM.
  65710. * DEPRECATED. Should use useExponentialShadowMap instead.
  65711. */
  65712. get: function () {
  65713. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65714. return this.useExponentialShadowMap;
  65715. },
  65716. /**
  65717. * Sets the current filter is to VSM.
  65718. * DEPRECATED. Should use useExponentialShadowMap instead.
  65719. */
  65720. set: function (value) {
  65721. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65722. this.useExponentialShadowMap = value;
  65723. },
  65724. enumerable: true,
  65725. configurable: true
  65726. });
  65727. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65728. /**
  65729. * Gets if the current filter is set to blurred VSM.
  65730. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65731. */
  65732. get: function () {
  65733. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65734. return this.useBlurExponentialShadowMap;
  65735. },
  65736. /**
  65737. * Sets the current filter is to blurred VSM.
  65738. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65739. */
  65740. set: function (value) {
  65741. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65742. this.useBlurExponentialShadowMap = value;
  65743. },
  65744. enumerable: true,
  65745. configurable: true
  65746. });
  65747. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65748. /**
  65749. * Gets if the current filter is set to ESM.
  65750. */
  65751. get: function () {
  65752. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65753. },
  65754. /**
  65755. * Sets the current filter is to ESM.
  65756. */
  65757. set: function (value) {
  65758. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65759. return;
  65760. }
  65761. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65762. },
  65763. enumerable: true,
  65764. configurable: true
  65765. });
  65766. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65767. /**
  65768. * Gets if the current filter is set to filtered ESM.
  65769. */
  65770. get: function () {
  65771. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65772. },
  65773. /**
  65774. * Gets if the current filter is set to filtered ESM.
  65775. */
  65776. set: function (value) {
  65777. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65778. return;
  65779. }
  65780. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65781. },
  65782. enumerable: true,
  65783. configurable: true
  65784. });
  65785. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65786. /**
  65787. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65788. * exponential to prevent steep falloff artifacts).
  65789. */
  65790. get: function () {
  65791. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65792. },
  65793. /**
  65794. * Sets the current filter to "close ESM" (using the inverse of the
  65795. * exponential to prevent steep falloff artifacts).
  65796. */
  65797. set: function (value) {
  65798. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65799. return;
  65800. }
  65801. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65802. },
  65803. enumerable: true,
  65804. configurable: true
  65805. });
  65806. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65807. /**
  65808. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65809. * exponential to prevent steep falloff artifacts).
  65810. */
  65811. get: function () {
  65812. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65813. },
  65814. /**
  65815. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65816. * exponential to prevent steep falloff artifacts).
  65817. */
  65818. set: function (value) {
  65819. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65820. return;
  65821. }
  65822. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65823. },
  65824. enumerable: true,
  65825. configurable: true
  65826. });
  65827. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65828. /**
  65829. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65830. */
  65831. get: function () {
  65832. return this.filter === ShadowGenerator.FILTER_PCF;
  65833. },
  65834. /**
  65835. * Sets the current filter to "PCF" (percentage closer filtering).
  65836. */
  65837. set: function (value) {
  65838. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65839. return;
  65840. }
  65841. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65842. },
  65843. enumerable: true,
  65844. configurable: true
  65845. });
  65846. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65847. /**
  65848. * Gets the PCF or PCSS Quality.
  65849. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65850. */
  65851. get: function () {
  65852. return this._filteringQuality;
  65853. },
  65854. /**
  65855. * Sets the PCF or PCSS Quality.
  65856. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65857. */
  65858. set: function (filteringQuality) {
  65859. this._filteringQuality = filteringQuality;
  65860. },
  65861. enumerable: true,
  65862. configurable: true
  65863. });
  65864. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65865. /**
  65866. * Gets if the current filter is set to "PCSS" (contact hardening).
  65867. */
  65868. get: function () {
  65869. return this.filter === ShadowGenerator.FILTER_PCSS;
  65870. },
  65871. /**
  65872. * Sets the current filter to "PCSS" (contact hardening).
  65873. */
  65874. set: function (value) {
  65875. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65876. return;
  65877. }
  65878. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65879. },
  65880. enumerable: true,
  65881. configurable: true
  65882. });
  65883. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65884. /**
  65885. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65886. * Using a ratio helps keeping shape stability independently of the map size.
  65887. *
  65888. * It does not account for the light projection as it was having too much
  65889. * instability during the light setup or during light position changes.
  65890. *
  65891. * Only valid if useContactHardeningShadow is true.
  65892. */
  65893. get: function () {
  65894. return this._contactHardeningLightSizeUVRatio;
  65895. },
  65896. /**
  65897. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65898. * Using a ratio helps keeping shape stability independently of the map size.
  65899. *
  65900. * It does not account for the light projection as it was having too much
  65901. * instability during the light setup or during light position changes.
  65902. *
  65903. * Only valid if useContactHardeningShadow is true.
  65904. */
  65905. set: function (contactHardeningLightSizeUVRatio) {
  65906. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65907. },
  65908. enumerable: true,
  65909. configurable: true
  65910. });
  65911. /**
  65912. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65913. * 0 means strongest and 1 would means no shadow.
  65914. * @returns the darkness.
  65915. */
  65916. ShadowGenerator.prototype.getDarkness = function () {
  65917. return this._darkness;
  65918. };
  65919. /**
  65920. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65921. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65922. * @returns the shadow generator allowing fluent coding.
  65923. */
  65924. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65925. if (darkness >= 1.0)
  65926. this._darkness = 1.0;
  65927. else if (darkness <= 0.0)
  65928. this._darkness = 0.0;
  65929. else
  65930. this._darkness = darkness;
  65931. return this;
  65932. };
  65933. /**
  65934. * Sets the ability to have transparent shadow (boolean).
  65935. * @param transparent True if transparent else False
  65936. * @returns the shadow generator allowing fluent coding
  65937. */
  65938. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65939. this._transparencyShadow = transparent;
  65940. return this;
  65941. };
  65942. /**
  65943. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65944. * @returns The render target texture if present otherwise, null
  65945. */
  65946. ShadowGenerator.prototype.getShadowMap = function () {
  65947. return this._shadowMap;
  65948. };
  65949. /**
  65950. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65951. * @returns The render target texture if the shadow map is present otherwise, null
  65952. */
  65953. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65954. if (this._shadowMap2) {
  65955. return this._shadowMap2;
  65956. }
  65957. return this._shadowMap;
  65958. };
  65959. /**
  65960. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65961. * @param mesh Mesh to add
  65962. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65963. * @returns the Shadow Generator itself
  65964. */
  65965. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65966. if (includeDescendants === void 0) { includeDescendants = true; }
  65967. if (!this._shadowMap) {
  65968. return this;
  65969. }
  65970. if (!this._shadowMap.renderList) {
  65971. this._shadowMap.renderList = [];
  65972. }
  65973. this._shadowMap.renderList.push(mesh);
  65974. if (includeDescendants) {
  65975. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65976. }
  65977. return this;
  65978. var _a;
  65979. };
  65980. /**
  65981. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65982. * @param mesh Mesh to remove
  65983. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65984. * @returns the Shadow Generator itself
  65985. */
  65986. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65987. if (includeDescendants === void 0) { includeDescendants = true; }
  65988. if (!this._shadowMap || !this._shadowMap.renderList) {
  65989. return this;
  65990. }
  65991. var index = this._shadowMap.renderList.indexOf(mesh);
  65992. if (index !== -1) {
  65993. this._shadowMap.renderList.splice(index, 1);
  65994. }
  65995. if (includeDescendants) {
  65996. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65997. var child = _a[_i];
  65998. this.removeShadowCaster(child);
  65999. }
  66000. }
  66001. return this;
  66002. };
  66003. /**
  66004. * Returns the associated light object.
  66005. * @returns the light generating the shadow
  66006. */
  66007. ShadowGenerator.prototype.getLight = function () {
  66008. return this._light;
  66009. };
  66010. ShadowGenerator.prototype._initializeGenerator = function () {
  66011. this._light._markMeshesAsLightDirty();
  66012. this._initializeShadowMap();
  66013. };
  66014. ShadowGenerator.prototype._initializeShadowMap = function () {
  66015. var _this = this;
  66016. // Render target
  66017. var engine = this._scene.getEngine();
  66018. if (engine.webGLVersion > 1) {
  66019. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66020. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66021. }
  66022. else {
  66023. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66024. }
  66025. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66026. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66027. this._shadowMap.anisotropicFilteringLevel = 1;
  66028. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66029. this._shadowMap.renderParticles = false;
  66030. this._shadowMap.ignoreCameraViewport = true;
  66031. // Record Face Index before render.
  66032. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66033. _this._currentFaceIndex = faceIndex;
  66034. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66035. engine.setColorWrite(false);
  66036. }
  66037. });
  66038. // Custom render function.
  66039. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66040. // Blur if required afer render.
  66041. this._shadowMap.onAfterUnbindObservable.add(function () {
  66042. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66043. engine.setColorWrite(true);
  66044. }
  66045. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66046. return;
  66047. }
  66048. var shadowMap = _this.getShadowMapForRendering();
  66049. if (shadowMap) {
  66050. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66051. }
  66052. });
  66053. // Clear according to the chosen filter.
  66054. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66055. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66056. this._shadowMap.onClearObservable.add(function (engine) {
  66057. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66058. engine.clear(clearOne, false, true, false);
  66059. }
  66060. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66061. engine.clear(clearZero, true, true, false);
  66062. }
  66063. else {
  66064. engine.clear(clearOne, true, true, false);
  66065. }
  66066. });
  66067. };
  66068. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66069. var _this = this;
  66070. var engine = this._scene.getEngine();
  66071. var targetSize = this._mapSize / this.blurScale;
  66072. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66073. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66074. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66075. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66076. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66077. }
  66078. if (this.useKernelBlur) {
  66079. 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);
  66080. this._kernelBlurXPostprocess.width = targetSize;
  66081. this._kernelBlurXPostprocess.height = targetSize;
  66082. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66083. effect.setTexture("textureSampler", _this._shadowMap);
  66084. });
  66085. 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);
  66086. this._kernelBlurXPostprocess.autoClear = false;
  66087. this._kernelBlurYPostprocess.autoClear = false;
  66088. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66089. this._kernelBlurXPostprocess.packedFloat = true;
  66090. this._kernelBlurYPostprocess.packedFloat = true;
  66091. }
  66092. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66093. }
  66094. else {
  66095. 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);
  66096. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66097. effect.setFloat2("screenSize", targetSize, targetSize);
  66098. effect.setTexture("textureSampler", _this._shadowMap);
  66099. });
  66100. this._boxBlurPostprocess.autoClear = false;
  66101. this._blurPostProcesses = [this._boxBlurPostprocess];
  66102. }
  66103. };
  66104. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66105. var index;
  66106. var engine = this._scene.getEngine();
  66107. if (depthOnlySubMeshes.length) {
  66108. engine.setColorWrite(false);
  66109. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66110. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66111. }
  66112. engine.setColorWrite(true);
  66113. }
  66114. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66115. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66116. }
  66117. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66118. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66119. }
  66120. if (this._transparencyShadow) {
  66121. for (index = 0; index < transparentSubMeshes.length; index++) {
  66122. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66123. }
  66124. }
  66125. };
  66126. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66127. var _this = this;
  66128. var mesh = subMesh.getRenderingMesh();
  66129. var scene = this._scene;
  66130. var engine = scene.getEngine();
  66131. var material = subMesh.getMaterial();
  66132. if (!material) {
  66133. return;
  66134. }
  66135. // Culling
  66136. engine.setState(material.backFaceCulling);
  66137. // Managing instances
  66138. var batch = mesh._getInstancesRenderList(subMesh._id);
  66139. if (batch.mustReturn) {
  66140. return;
  66141. }
  66142. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66143. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66144. engine.enableEffect(this._effect);
  66145. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66146. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66147. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66148. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66149. this._effect.setVector3("lightData", this._cachedDirection);
  66150. }
  66151. else {
  66152. this._effect.setVector3("lightData", this._cachedPosition);
  66153. }
  66154. if (scene.activeCamera) {
  66155. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66156. }
  66157. // Alpha test
  66158. if (material && material.needAlphaTesting()) {
  66159. var alphaTexture = material.getAlphaTestTexture();
  66160. if (alphaTexture) {
  66161. this._effect.setTexture("diffuseSampler", alphaTexture);
  66162. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66163. }
  66164. }
  66165. // Bones
  66166. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66167. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66168. }
  66169. // Morph targets
  66170. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66171. if (this.forceBackFacesOnly) {
  66172. engine.setState(true, 0, false, true);
  66173. }
  66174. // Draw
  66175. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66176. if (this.forceBackFacesOnly) {
  66177. engine.setState(true, 0, false, false);
  66178. }
  66179. }
  66180. else {
  66181. // Need to reset refresh rate of the shadowMap
  66182. if (this._shadowMap) {
  66183. this._shadowMap.resetRefreshCounter();
  66184. }
  66185. }
  66186. };
  66187. ShadowGenerator.prototype._applyFilterValues = function () {
  66188. if (!this._shadowMap) {
  66189. return;
  66190. }
  66191. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66192. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66193. }
  66194. else {
  66195. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66196. }
  66197. };
  66198. /**
  66199. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66200. * @param onCompiled Callback triggered at the and of the effects compilation
  66201. * @param options Sets of optional options forcing the compilation with different modes
  66202. */
  66203. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66204. var _this = this;
  66205. var localOptions = __assign({ useInstances: false }, options);
  66206. var shadowMap = this.getShadowMap();
  66207. if (!shadowMap) {
  66208. if (onCompiled) {
  66209. onCompiled(this);
  66210. }
  66211. return;
  66212. }
  66213. var renderList = shadowMap.renderList;
  66214. if (!renderList) {
  66215. if (onCompiled) {
  66216. onCompiled(this);
  66217. }
  66218. return;
  66219. }
  66220. var subMeshes = new Array();
  66221. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66222. var mesh = renderList_1[_i];
  66223. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66224. }
  66225. if (subMeshes.length === 0) {
  66226. if (onCompiled) {
  66227. onCompiled(this);
  66228. }
  66229. return;
  66230. }
  66231. var currentIndex = 0;
  66232. var checkReady = function () {
  66233. if (!_this._scene || !_this._scene.getEngine()) {
  66234. return;
  66235. }
  66236. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66237. currentIndex++;
  66238. if (currentIndex >= subMeshes.length) {
  66239. if (onCompiled) {
  66240. onCompiled(_this);
  66241. }
  66242. return;
  66243. }
  66244. }
  66245. setTimeout(checkReady, 16);
  66246. };
  66247. checkReady();
  66248. };
  66249. /**
  66250. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66251. * @param options Sets of optional options forcing the compilation with different modes
  66252. * @returns A promise that resolves when the compilation completes
  66253. */
  66254. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66255. var _this = this;
  66256. return new Promise(function (resolve) {
  66257. _this.forceCompilation(function () {
  66258. resolve();
  66259. }, options);
  66260. });
  66261. };
  66262. /**
  66263. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66264. * @param subMesh The submesh we want to render in the shadow map
  66265. * @param useInstances Defines wether will draw in the map using instances
  66266. * @returns true if ready otherwise, false
  66267. */
  66268. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66269. var defines = [];
  66270. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66271. defines.push("#define FLOAT");
  66272. }
  66273. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66274. defines.push("#define ESM");
  66275. }
  66276. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66277. defines.push("#define DEPTHTEXTURE");
  66278. }
  66279. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66280. var mesh = subMesh.getMesh();
  66281. var material = subMesh.getMaterial();
  66282. // Normal bias.
  66283. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66284. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66285. defines.push("#define NORMAL");
  66286. if (mesh.nonUniformScaling) {
  66287. defines.push("#define NONUNIFORMSCALING");
  66288. }
  66289. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66290. defines.push("#define DIRECTIONINLIGHTDATA");
  66291. }
  66292. }
  66293. // Alpha test
  66294. if (material && material.needAlphaTesting()) {
  66295. var alphaTexture = material.getAlphaTestTexture();
  66296. if (alphaTexture) {
  66297. defines.push("#define ALPHATEST");
  66298. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66299. attribs.push(BABYLON.VertexBuffer.UVKind);
  66300. defines.push("#define UV1");
  66301. }
  66302. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66303. if (alphaTexture.coordinatesIndex === 1) {
  66304. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66305. defines.push("#define UV2");
  66306. }
  66307. }
  66308. }
  66309. }
  66310. // Bones
  66311. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66312. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66313. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66314. if (mesh.numBoneInfluencers > 4) {
  66315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66317. }
  66318. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66319. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66320. }
  66321. else {
  66322. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66323. }
  66324. // Morph targets
  66325. var manager = mesh.morphTargetManager;
  66326. var morphInfluencers = 0;
  66327. if (manager) {
  66328. if (manager.numInfluencers > 0) {
  66329. defines.push("#define MORPHTARGETS");
  66330. morphInfluencers = manager.numInfluencers;
  66331. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66332. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66333. }
  66334. }
  66335. // Instances
  66336. if (useInstances) {
  66337. defines.push("#define INSTANCES");
  66338. attribs.push("world0");
  66339. attribs.push("world1");
  66340. attribs.push("world2");
  66341. attribs.push("world3");
  66342. }
  66343. // Get correct effect
  66344. var join = defines.join("\n");
  66345. if (this._cachedDefines !== join) {
  66346. this._cachedDefines = join;
  66347. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66348. }
  66349. if (!this._effect.isReady()) {
  66350. return false;
  66351. }
  66352. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66353. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66354. this._initializeBlurRTTAndPostProcesses();
  66355. }
  66356. }
  66357. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66358. return false;
  66359. }
  66360. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66361. return false;
  66362. }
  66363. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66364. return false;
  66365. }
  66366. return true;
  66367. };
  66368. /**
  66369. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66370. * @param defines Defines of the material we want to update
  66371. * @param lightIndex Index of the light in the enabled light list of the material
  66372. */
  66373. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66374. var scene = this._scene;
  66375. var light = this._light;
  66376. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66377. return;
  66378. }
  66379. defines["SHADOW" + lightIndex] = true;
  66380. if (this.useContactHardeningShadow) {
  66381. defines["SHADOWPCSS" + lightIndex] = true;
  66382. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66383. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66384. }
  66385. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66386. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66387. }
  66388. // else default to high.
  66389. }
  66390. if (this.usePercentageCloserFiltering) {
  66391. defines["SHADOWPCF" + lightIndex] = true;
  66392. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66393. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66394. }
  66395. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66396. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66397. }
  66398. // else default to high.
  66399. }
  66400. else if (this.usePoissonSampling) {
  66401. defines["SHADOWPOISSON" + lightIndex] = true;
  66402. }
  66403. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66404. defines["SHADOWESM" + lightIndex] = true;
  66405. }
  66406. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66407. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66408. }
  66409. if (light.needCube()) {
  66410. defines["SHADOWCUBE" + lightIndex] = true;
  66411. }
  66412. };
  66413. /**
  66414. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66415. * defined in the generator but impacting the effect).
  66416. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66417. * @param effect The effect we are binfing the information for
  66418. */
  66419. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66420. var light = this._light;
  66421. var scene = this._scene;
  66422. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66423. return;
  66424. }
  66425. var camera = scene.activeCamera;
  66426. if (!camera) {
  66427. return;
  66428. }
  66429. var shadowMap = this.getShadowMap();
  66430. if (!shadowMap) {
  66431. return;
  66432. }
  66433. if (!light.needCube()) {
  66434. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66435. }
  66436. // Only PCF uses depth stencil texture.
  66437. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66438. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66439. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66440. }
  66441. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66442. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66443. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66444. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66445. }
  66446. else {
  66447. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66448. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66449. }
  66450. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66451. };
  66452. /**
  66453. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66454. * (eq to shadow prjection matrix * light transform matrix)
  66455. * @returns The transform matrix used to create the shadow map
  66456. */
  66457. ShadowGenerator.prototype.getTransformMatrix = function () {
  66458. var scene = this._scene;
  66459. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66460. return this._transformMatrix;
  66461. }
  66462. this._currentRenderID = scene.getRenderId();
  66463. this._currentFaceIndexCache = this._currentFaceIndex;
  66464. var lightPosition = this._light.position;
  66465. if (this._light.computeTransformedInformation()) {
  66466. lightPosition = this._light.transformedPosition;
  66467. }
  66468. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66469. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66470. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66471. }
  66472. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66473. this._cachedPosition.copyFrom(lightPosition);
  66474. this._cachedDirection.copyFrom(this._lightDirection);
  66475. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66476. var shadowMap = this.getShadowMap();
  66477. if (shadowMap) {
  66478. var renderList = shadowMap.renderList;
  66479. if (renderList) {
  66480. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66481. }
  66482. }
  66483. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66484. }
  66485. return this._transformMatrix;
  66486. };
  66487. /**
  66488. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66489. * Cube and 2D textures for instance.
  66490. */
  66491. ShadowGenerator.prototype.recreateShadowMap = function () {
  66492. var shadowMap = this._shadowMap;
  66493. if (!shadowMap) {
  66494. return;
  66495. }
  66496. // Track render list.
  66497. var renderList = shadowMap.renderList;
  66498. // Clean up existing data.
  66499. this._disposeRTTandPostProcesses();
  66500. // Reinitializes.
  66501. this._initializeGenerator();
  66502. // Reaffect the filter to ensure a correct fallback if necessary.
  66503. this.filter = this.filter;
  66504. // Reaffect the filter.
  66505. this._applyFilterValues();
  66506. // Reaffect Render List.
  66507. this._shadowMap.renderList = renderList;
  66508. };
  66509. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66510. if (this._shadowMap2) {
  66511. this._shadowMap2.dispose();
  66512. this._shadowMap2 = null;
  66513. }
  66514. if (this._boxBlurPostprocess) {
  66515. this._boxBlurPostprocess.dispose();
  66516. this._boxBlurPostprocess = null;
  66517. }
  66518. if (this._kernelBlurXPostprocess) {
  66519. this._kernelBlurXPostprocess.dispose();
  66520. this._kernelBlurXPostprocess = null;
  66521. }
  66522. if (this._kernelBlurYPostprocess) {
  66523. this._kernelBlurYPostprocess.dispose();
  66524. this._kernelBlurYPostprocess = null;
  66525. }
  66526. this._blurPostProcesses = [];
  66527. };
  66528. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66529. if (this._shadowMap) {
  66530. this._shadowMap.dispose();
  66531. this._shadowMap = null;
  66532. }
  66533. this._disposeBlurPostProcesses();
  66534. };
  66535. /**
  66536. * Disposes the ShadowGenerator.
  66537. * Returns nothing.
  66538. */
  66539. ShadowGenerator.prototype.dispose = function () {
  66540. this._disposeRTTandPostProcesses();
  66541. if (this._light) {
  66542. this._light._shadowGenerator = null;
  66543. this._light._markMeshesAsLightDirty();
  66544. }
  66545. };
  66546. /**
  66547. * Serializes the shadow generator setup to a json object.
  66548. * @returns The serialized JSON object
  66549. */
  66550. ShadowGenerator.prototype.serialize = function () {
  66551. var serializationObject = {};
  66552. var shadowMap = this.getShadowMap();
  66553. if (!shadowMap) {
  66554. return serializationObject;
  66555. }
  66556. serializationObject.lightId = this._light.id;
  66557. serializationObject.mapSize = shadowMap.getRenderSize();
  66558. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66559. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66560. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66561. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66562. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66563. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66564. serializationObject.depthScale = this.depthScale;
  66565. serializationObject.darkness = this.getDarkness();
  66566. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66567. serializationObject.blurKernel = this.blurKernel;
  66568. serializationObject.blurScale = this.blurScale;
  66569. serializationObject.useKernelBlur = this.useKernelBlur;
  66570. serializationObject.transparencyShadow = this._transparencyShadow;
  66571. serializationObject.bias = this.bias;
  66572. serializationObject.normalBias = this.normalBias;
  66573. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66574. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66575. serializationObject.filteringQuality = this.filteringQuality;
  66576. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66577. serializationObject.renderList = [];
  66578. if (shadowMap.renderList) {
  66579. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66580. var mesh = shadowMap.renderList[meshIndex];
  66581. serializationObject.renderList.push(mesh.id);
  66582. }
  66583. }
  66584. return serializationObject;
  66585. };
  66586. /**
  66587. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66588. * @param parsedShadowGenerator The JSON object to parse
  66589. * @param scene The scene to create the shadow map for
  66590. * @returns The parsed shadow generator
  66591. */
  66592. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66593. //casting to point light, as light is missing the position attr and typescript complains.
  66594. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66595. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66596. var shadowMap = shadowGenerator.getShadowMap();
  66597. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66598. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66599. meshes.forEach(function (mesh) {
  66600. if (!shadowMap) {
  66601. return;
  66602. }
  66603. if (!shadowMap.renderList) {
  66604. shadowMap.renderList = [];
  66605. }
  66606. shadowMap.renderList.push(mesh);
  66607. });
  66608. }
  66609. if (parsedShadowGenerator.usePoissonSampling) {
  66610. shadowGenerator.usePoissonSampling = true;
  66611. }
  66612. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66613. shadowGenerator.useExponentialShadowMap = true;
  66614. }
  66615. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66616. shadowGenerator.useBlurExponentialShadowMap = true;
  66617. }
  66618. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66619. shadowGenerator.useCloseExponentialShadowMap = true;
  66620. }
  66621. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66622. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66623. }
  66624. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66625. shadowGenerator.usePercentageCloserFiltering = true;
  66626. }
  66627. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66628. shadowGenerator.useContactHardeningShadow = true;
  66629. }
  66630. if (parsedShadowGenerator.filteringQuality) {
  66631. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66632. }
  66633. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66634. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66635. }
  66636. // Backward compat
  66637. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66638. shadowGenerator.useExponentialShadowMap = true;
  66639. }
  66640. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66641. shadowGenerator.useBlurExponentialShadowMap = true;
  66642. }
  66643. if (parsedShadowGenerator.depthScale) {
  66644. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66645. }
  66646. if (parsedShadowGenerator.blurScale) {
  66647. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66648. }
  66649. if (parsedShadowGenerator.blurBoxOffset) {
  66650. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66651. }
  66652. if (parsedShadowGenerator.useKernelBlur) {
  66653. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66654. }
  66655. if (parsedShadowGenerator.blurKernel) {
  66656. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66657. }
  66658. if (parsedShadowGenerator.bias !== undefined) {
  66659. shadowGenerator.bias = parsedShadowGenerator.bias;
  66660. }
  66661. if (parsedShadowGenerator.normalBias !== undefined) {
  66662. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66663. }
  66664. if (parsedShadowGenerator.darkness) {
  66665. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66666. }
  66667. if (parsedShadowGenerator.transparencyShadow) {
  66668. shadowGenerator.setTransparencyShadow(true);
  66669. }
  66670. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66671. return shadowGenerator;
  66672. };
  66673. /**
  66674. * Shadow generator mode None: no filtering applied.
  66675. */
  66676. ShadowGenerator.FILTER_NONE = 0;
  66677. /**
  66678. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66679. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66680. */
  66681. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66682. /**
  66683. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66684. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66685. */
  66686. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66687. /**
  66688. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66689. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66690. */
  66691. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66692. /**
  66693. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66694. * edge artifacts on steep falloff.
  66695. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66696. */
  66697. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66698. /**
  66699. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66700. * edge artifacts on steep falloff.
  66701. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66702. */
  66703. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66704. /**
  66705. * Shadow generator mode PCF: Percentage Closer Filtering
  66706. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66707. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66708. */
  66709. ShadowGenerator.FILTER_PCF = 6;
  66710. /**
  66711. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66712. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66713. * Contact Hardening
  66714. */
  66715. ShadowGenerator.FILTER_PCSS = 7;
  66716. /**
  66717. * Reserved for PCF and PCSS
  66718. * Highest Quality.
  66719. *
  66720. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66721. *
  66722. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66723. */
  66724. ShadowGenerator.QUALITY_HIGH = 0;
  66725. /**
  66726. * Reserved for PCF and PCSS
  66727. * Good tradeoff for quality/perf cross devices
  66728. *
  66729. * Execute PCF on a 3*3 kernel.
  66730. *
  66731. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66732. */
  66733. ShadowGenerator.QUALITY_MEDIUM = 1;
  66734. /**
  66735. * Reserved for PCF and PCSS
  66736. * The lowest quality but the fastest.
  66737. *
  66738. * Execute PCF on a 1*1 kernel.
  66739. *
  66740. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66741. */
  66742. ShadowGenerator.QUALITY_LOW = 2;
  66743. return ShadowGenerator;
  66744. }());
  66745. BABYLON.ShadowGenerator = ShadowGenerator;
  66746. })(BABYLON || (BABYLON = {}));
  66747. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66748. var BABYLON;
  66749. (function (BABYLON) {
  66750. var DefaultLoadingScreen = /** @class */ (function () {
  66751. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66752. if (_loadingText === void 0) { _loadingText = ""; }
  66753. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66754. var _this = this;
  66755. this._renderingCanvas = _renderingCanvas;
  66756. this._loadingText = _loadingText;
  66757. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66758. // Resize
  66759. this._resizeLoadingUI = function () {
  66760. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66761. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66762. if (!_this._loadingDiv) {
  66763. return;
  66764. }
  66765. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66766. _this._loadingDiv.style.left = canvasRect.left + "px";
  66767. _this._loadingDiv.style.top = canvasRect.top + "px";
  66768. _this._loadingDiv.style.width = canvasRect.width + "px";
  66769. _this._loadingDiv.style.height = canvasRect.height + "px";
  66770. };
  66771. }
  66772. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66773. if (this._loadingDiv) {
  66774. // Do not add a loading screen if there is already one
  66775. return;
  66776. }
  66777. this._loadingDiv = document.createElement("div");
  66778. this._loadingDiv.id = "babylonjsLoadingDiv";
  66779. this._loadingDiv.style.opacity = "0";
  66780. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66781. this._loadingDiv.style.pointerEvents = "none";
  66782. // Loading text
  66783. this._loadingTextDiv = document.createElement("div");
  66784. this._loadingTextDiv.style.position = "absolute";
  66785. this._loadingTextDiv.style.left = "0";
  66786. this._loadingTextDiv.style.top = "50%";
  66787. this._loadingTextDiv.style.marginTop = "80px";
  66788. this._loadingTextDiv.style.width = "100%";
  66789. this._loadingTextDiv.style.height = "20px";
  66790. this._loadingTextDiv.style.fontFamily = "Arial";
  66791. this._loadingTextDiv.style.fontSize = "14px";
  66792. this._loadingTextDiv.style.color = "white";
  66793. this._loadingTextDiv.style.textAlign = "center";
  66794. this._loadingTextDiv.innerHTML = "Loading";
  66795. this._loadingDiv.appendChild(this._loadingTextDiv);
  66796. //set the predefined text
  66797. this._loadingTextDiv.innerHTML = this._loadingText;
  66798. // Generating keyframes
  66799. var style = document.createElement('style');
  66800. style.type = 'text/css';
  66801. 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 }";
  66802. style.innerHTML = keyFrames;
  66803. document.getElementsByTagName('head')[0].appendChild(style);
  66804. // Loading img
  66805. var imgBack = new Image();
  66806. 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";
  66807. imgBack.style.position = "absolute";
  66808. imgBack.style.left = "50%";
  66809. imgBack.style.top = "50%";
  66810. imgBack.style.marginLeft = "-60px";
  66811. imgBack.style.marginTop = "-60px";
  66812. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66813. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66814. imgBack.style.transformOrigin = "50% 50%";
  66815. imgBack.style.webkitTransformOrigin = "50% 50%";
  66816. this._loadingDiv.appendChild(imgBack);
  66817. this._resizeLoadingUI();
  66818. window.addEventListener("resize", this._resizeLoadingUI);
  66819. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66820. document.body.appendChild(this._loadingDiv);
  66821. this._loadingDiv.style.opacity = "1";
  66822. };
  66823. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66824. var _this = this;
  66825. if (!this._loadingDiv) {
  66826. return;
  66827. }
  66828. var onTransitionEnd = function () {
  66829. if (!_this._loadingDiv) {
  66830. return;
  66831. }
  66832. document.body.removeChild(_this._loadingDiv);
  66833. window.removeEventListener("resize", _this._resizeLoadingUI);
  66834. _this._loadingDiv = null;
  66835. };
  66836. this._loadingDiv.style.opacity = "0";
  66837. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66838. };
  66839. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66840. set: function (text) {
  66841. this._loadingText = text;
  66842. if (this._loadingTextDiv) {
  66843. this._loadingTextDiv.innerHTML = this._loadingText;
  66844. }
  66845. },
  66846. enumerable: true,
  66847. configurable: true
  66848. });
  66849. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66850. get: function () {
  66851. return this._loadingDivBackgroundColor;
  66852. },
  66853. set: function (color) {
  66854. this._loadingDivBackgroundColor = color;
  66855. if (!this._loadingDiv) {
  66856. return;
  66857. }
  66858. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66859. },
  66860. enumerable: true,
  66861. configurable: true
  66862. });
  66863. return DefaultLoadingScreen;
  66864. }());
  66865. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66866. })(BABYLON || (BABYLON = {}));
  66867. //# sourceMappingURL=babylon.loadingScreen.js.map
  66868. var BABYLON;
  66869. (function (BABYLON) {
  66870. var SceneLoaderProgressEvent = /** @class */ (function () {
  66871. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66872. this.lengthComputable = lengthComputable;
  66873. this.loaded = loaded;
  66874. this.total = total;
  66875. }
  66876. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66877. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66878. };
  66879. return SceneLoaderProgressEvent;
  66880. }());
  66881. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66882. var SceneLoader = /** @class */ (function () {
  66883. function SceneLoader() {
  66884. }
  66885. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66886. get: function () {
  66887. return 0;
  66888. },
  66889. enumerable: true,
  66890. configurable: true
  66891. });
  66892. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66893. get: function () {
  66894. return 1;
  66895. },
  66896. enumerable: true,
  66897. configurable: true
  66898. });
  66899. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66900. get: function () {
  66901. return 2;
  66902. },
  66903. enumerable: true,
  66904. configurable: true
  66905. });
  66906. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66907. get: function () {
  66908. return 3;
  66909. },
  66910. enumerable: true,
  66911. configurable: true
  66912. });
  66913. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66914. get: function () {
  66915. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66916. },
  66917. set: function (value) {
  66918. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66919. },
  66920. enumerable: true,
  66921. configurable: true
  66922. });
  66923. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66924. get: function () {
  66925. return SceneLoader._ShowLoadingScreen;
  66926. },
  66927. set: function (value) {
  66928. SceneLoader._ShowLoadingScreen = value;
  66929. },
  66930. enumerable: true,
  66931. configurable: true
  66932. });
  66933. Object.defineProperty(SceneLoader, "loggingLevel", {
  66934. get: function () {
  66935. return SceneLoader._loggingLevel;
  66936. },
  66937. set: function (value) {
  66938. SceneLoader._loggingLevel = value;
  66939. },
  66940. enumerable: true,
  66941. configurable: true
  66942. });
  66943. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66944. get: function () {
  66945. return SceneLoader._CleanBoneMatrixWeights;
  66946. },
  66947. set: function (value) {
  66948. SceneLoader._CleanBoneMatrixWeights = value;
  66949. },
  66950. enumerable: true,
  66951. configurable: true
  66952. });
  66953. SceneLoader._getDefaultPlugin = function () {
  66954. return SceneLoader._registeredPlugins[".babylon"];
  66955. };
  66956. SceneLoader._getPluginForExtension = function (extension) {
  66957. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66958. if (registeredPlugin) {
  66959. return registeredPlugin;
  66960. }
  66961. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66962. return SceneLoader._getDefaultPlugin();
  66963. };
  66964. SceneLoader._getPluginForDirectLoad = function (data) {
  66965. for (var extension in SceneLoader._registeredPlugins) {
  66966. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66967. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66968. return SceneLoader._registeredPlugins[extension];
  66969. }
  66970. }
  66971. return SceneLoader._getDefaultPlugin();
  66972. };
  66973. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66974. if (sceneFilename.name) {
  66975. sceneFilename = sceneFilename.name;
  66976. }
  66977. var queryStringPosition = sceneFilename.indexOf("?");
  66978. if (queryStringPosition !== -1) {
  66979. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66980. }
  66981. var dotPosition = sceneFilename.lastIndexOf(".");
  66982. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66983. return SceneLoader._getPluginForExtension(extension);
  66984. };
  66985. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66986. SceneLoader._getDirectLoad = function (sceneFilename) {
  66987. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66988. return sceneFilename.substr(5);
  66989. }
  66990. return null;
  66991. };
  66992. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66993. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66994. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66995. var plugin;
  66996. if (registeredPlugin.plugin.createPlugin) {
  66997. plugin = registeredPlugin.plugin.createPlugin();
  66998. }
  66999. else {
  67000. plugin = registeredPlugin.plugin;
  67001. }
  67002. var useArrayBuffer = registeredPlugin.isBinary;
  67003. var database;
  67004. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67005. var dataCallback = function (data, responseURL) {
  67006. if (scene.isDisposed) {
  67007. onError("Scene has been disposed");
  67008. return;
  67009. }
  67010. scene.database = database;
  67011. onSuccess(plugin, data, responseURL);
  67012. };
  67013. var request = null;
  67014. var pluginDisposed = false;
  67015. var onDisposeObservable = plugin.onDisposeObservable;
  67016. if (onDisposeObservable) {
  67017. onDisposeObservable.add(function () {
  67018. pluginDisposed = true;
  67019. if (request) {
  67020. request.abort();
  67021. request = null;
  67022. }
  67023. onDispose();
  67024. });
  67025. }
  67026. var manifestChecked = function () {
  67027. if (pluginDisposed) {
  67028. return;
  67029. }
  67030. var url = rootUrl + sceneFilename;
  67031. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67032. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67033. } : undefined, database, useArrayBuffer, function (request, exception) {
  67034. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67035. });
  67036. };
  67037. if (directLoad) {
  67038. dataCallback(directLoad);
  67039. return plugin;
  67040. }
  67041. if (rootUrl.indexOf("file:") === -1) {
  67042. var engine = scene.getEngine();
  67043. var canUseOfflineSupport = engine.enableOfflineSupport;
  67044. if (canUseOfflineSupport) {
  67045. // Also check for exceptions
  67046. var exceptionFound = false;
  67047. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67048. var regex = _a[_i];
  67049. if (regex.test(rootUrl + sceneFilename)) {
  67050. exceptionFound = true;
  67051. break;
  67052. }
  67053. }
  67054. canUseOfflineSupport = !exceptionFound;
  67055. }
  67056. if (canUseOfflineSupport) {
  67057. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67058. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67059. }
  67060. else {
  67061. manifestChecked();
  67062. }
  67063. }
  67064. // Loading file from disk via input file or drag'n'drop
  67065. else {
  67066. var fileOrString = sceneFilename;
  67067. if (fileOrString.name) { // File
  67068. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67069. }
  67070. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67071. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67072. }
  67073. else {
  67074. onError("Unable to find file named " + sceneFilename);
  67075. }
  67076. }
  67077. return plugin;
  67078. };
  67079. // Public functions
  67080. SceneLoader.GetPluginForExtension = function (extension) {
  67081. return SceneLoader._getPluginForExtension(extension).plugin;
  67082. };
  67083. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67084. return !!SceneLoader._registeredPlugins[extension];
  67085. };
  67086. SceneLoader.RegisterPlugin = function (plugin) {
  67087. if (typeof plugin.extensions === "string") {
  67088. var extension = plugin.extensions;
  67089. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67090. plugin: plugin,
  67091. isBinary: false
  67092. };
  67093. }
  67094. else {
  67095. var extensions = plugin.extensions;
  67096. Object.keys(extensions).forEach(function (extension) {
  67097. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67098. plugin: plugin,
  67099. isBinary: extensions[extension].isBinary
  67100. };
  67101. });
  67102. }
  67103. };
  67104. /**
  67105. * Import meshes into a scene
  67106. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67107. * @param rootUrl a string that defines the root url for scene and resources
  67108. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67109. * @param scene the instance of BABYLON.Scene to append to
  67110. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67111. * @param onProgress a callback with a progress event for each file being loaded
  67112. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67113. * @param pluginExtension the extension used to determine the plugin
  67114. * @returns The loaded plugin
  67115. */
  67116. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67117. if (onSuccess === void 0) { onSuccess = null; }
  67118. if (onProgress === void 0) { onProgress = null; }
  67119. if (onError === void 0) { onError = null; }
  67120. if (pluginExtension === void 0) { pluginExtension = null; }
  67121. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67122. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67123. return null;
  67124. }
  67125. var loadingToken = {};
  67126. scene._addPendingData(loadingToken);
  67127. var disposeHandler = function () {
  67128. scene._removePendingData(loadingToken);
  67129. };
  67130. var errorHandler = function (message, exception) {
  67131. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67132. if (onError) {
  67133. onError(scene, errorMessage, exception);
  67134. }
  67135. else {
  67136. BABYLON.Tools.Error(errorMessage);
  67137. // should the exception be thrown?
  67138. }
  67139. disposeHandler();
  67140. };
  67141. var progressHandler = onProgress ? function (event) {
  67142. try {
  67143. onProgress(event);
  67144. }
  67145. catch (e) {
  67146. errorHandler("Error in onProgress callback", e);
  67147. }
  67148. } : undefined;
  67149. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67150. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67151. if (onSuccess) {
  67152. try {
  67153. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67154. }
  67155. catch (e) {
  67156. errorHandler("Error in onSuccess callback", e);
  67157. }
  67158. }
  67159. scene._removePendingData(loadingToken);
  67160. };
  67161. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67162. if (plugin.rewriteRootURL) {
  67163. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67164. }
  67165. if (sceneFilename === "") {
  67166. if (sceneFilename === "") {
  67167. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67168. }
  67169. }
  67170. if (plugin.importMesh) {
  67171. var syncedPlugin = plugin;
  67172. var meshes = new Array();
  67173. var particleSystems = new Array();
  67174. var skeletons = new Array();
  67175. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67176. return;
  67177. }
  67178. scene.loadingPluginName = plugin.name;
  67179. successHandler(meshes, particleSystems, skeletons, []);
  67180. }
  67181. else {
  67182. var asyncedPlugin = plugin;
  67183. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67184. scene.loadingPluginName = plugin.name;
  67185. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67186. }).catch(function (error) {
  67187. errorHandler(error.message, error);
  67188. });
  67189. }
  67190. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67191. };
  67192. /**
  67193. * Import meshes into a scene
  67194. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67195. * @param rootUrl a string that defines the root url for scene and resources
  67196. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67197. * @param scene the instance of BABYLON.Scene to append to
  67198. * @param onProgress a callback with a progress event for each file being loaded
  67199. * @param pluginExtension the extension used to determine the plugin
  67200. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67201. */
  67202. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67203. if (onProgress === void 0) { onProgress = null; }
  67204. if (pluginExtension === void 0) { pluginExtension = null; }
  67205. return new Promise(function (resolve, reject) {
  67206. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67207. resolve({
  67208. meshes: meshes,
  67209. particleSystems: particleSystems,
  67210. skeletons: skeletons,
  67211. animationGroups: animationGroups
  67212. });
  67213. }, onProgress, function (scene, message, exception) {
  67214. reject(exception || new Error(message));
  67215. }, pluginExtension);
  67216. });
  67217. };
  67218. /**
  67219. * Load a scene
  67220. * @param rootUrl a string that defines the root url for scene and resources
  67221. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67222. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67223. * @param onSuccess a callback with the scene when import succeeds
  67224. * @param onProgress a callback with a progress event for each file being loaded
  67225. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67226. * @param pluginExtension the extension used to determine the plugin
  67227. * @returns The loaded plugin
  67228. */
  67229. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67230. if (onSuccess === void 0) { onSuccess = null; }
  67231. if (onProgress === void 0) { onProgress = null; }
  67232. if (onError === void 0) { onError = null; }
  67233. if (pluginExtension === void 0) { pluginExtension = null; }
  67234. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67235. };
  67236. /**
  67237. * Load a scene
  67238. * @param rootUrl a string that defines the root url for scene and resources
  67239. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67240. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67241. * @param onProgress a callback with a progress event for each file being loaded
  67242. * @param pluginExtension the extension used to determine the plugin
  67243. * @returns The loaded scene
  67244. */
  67245. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67246. if (onProgress === void 0) { onProgress = null; }
  67247. if (pluginExtension === void 0) { pluginExtension = null; }
  67248. return new Promise(function (resolve, reject) {
  67249. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67250. resolve(scene);
  67251. }, onProgress, function (scene, message, exception) {
  67252. reject(exception || new Error(message));
  67253. }, pluginExtension);
  67254. });
  67255. };
  67256. /**
  67257. * Append a scene
  67258. * @param rootUrl a string that defines the root url for scene and resources
  67259. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67260. * @param scene is the instance of BABYLON.Scene to append to
  67261. * @param onSuccess a callback with the scene when import succeeds
  67262. * @param onProgress a callback with a progress event for each file being loaded
  67263. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67264. * @param pluginExtension the extension used to determine the plugin
  67265. * @returns The loaded plugin
  67266. */
  67267. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67268. if (onSuccess === void 0) { onSuccess = null; }
  67269. if (onProgress === void 0) { onProgress = null; }
  67270. if (onError === void 0) { onError = null; }
  67271. if (pluginExtension === void 0) { pluginExtension = null; }
  67272. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67273. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67274. return null;
  67275. }
  67276. if (SceneLoader.ShowLoadingScreen) {
  67277. scene.getEngine().displayLoadingUI();
  67278. }
  67279. var loadingToken = {};
  67280. scene._addPendingData(loadingToken);
  67281. var disposeHandler = function () {
  67282. scene._removePendingData(loadingToken);
  67283. scene.getEngine().hideLoadingUI();
  67284. };
  67285. var errorHandler = function (message, exception) {
  67286. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67287. if (onError) {
  67288. onError(scene, errorMessage, exception);
  67289. }
  67290. else {
  67291. BABYLON.Tools.Error(errorMessage);
  67292. // should the exception be thrown?
  67293. }
  67294. disposeHandler();
  67295. };
  67296. var progressHandler = onProgress ? function (event) {
  67297. try {
  67298. onProgress(event);
  67299. }
  67300. catch (e) {
  67301. errorHandler("Error in onProgress callback", e);
  67302. }
  67303. } : undefined;
  67304. var successHandler = function () {
  67305. if (onSuccess) {
  67306. try {
  67307. onSuccess(scene);
  67308. }
  67309. catch (e) {
  67310. errorHandler("Error in onSuccess callback", e);
  67311. }
  67312. }
  67313. scene._removePendingData(loadingToken);
  67314. };
  67315. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67316. if (sceneFilename === "") {
  67317. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67318. }
  67319. if (plugin.load) {
  67320. var syncedPlugin = plugin;
  67321. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67322. return;
  67323. }
  67324. scene.loadingPluginName = plugin.name;
  67325. successHandler();
  67326. }
  67327. else {
  67328. var asyncedPlugin = plugin;
  67329. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67330. scene.loadingPluginName = plugin.name;
  67331. successHandler();
  67332. }).catch(function (error) {
  67333. errorHandler(error.message, error);
  67334. });
  67335. }
  67336. if (SceneLoader.ShowLoadingScreen) {
  67337. scene.executeWhenReady(function () {
  67338. scene.getEngine().hideLoadingUI();
  67339. });
  67340. }
  67341. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67342. };
  67343. /**
  67344. * Append a scene
  67345. * @param rootUrl a string that defines the root url for scene and resources
  67346. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67347. * @param scene is the instance of BABYLON.Scene to append to
  67348. * @param onProgress a callback with a progress event for each file being loaded
  67349. * @param pluginExtension the extension used to determine the plugin
  67350. * @returns The given scene
  67351. */
  67352. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67353. if (onProgress === void 0) { onProgress = null; }
  67354. if (pluginExtension === void 0) { pluginExtension = null; }
  67355. return new Promise(function (resolve, reject) {
  67356. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67357. resolve(scene);
  67358. }, onProgress, function (scene, message, exception) {
  67359. reject(exception || new Error(message));
  67360. }, pluginExtension);
  67361. });
  67362. };
  67363. /**
  67364. * Load a scene into an asset container
  67365. * @param rootUrl a string that defines the root url for scene and resources
  67366. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67367. * @param scene is the instance of BABYLON.Scene to append to
  67368. * @param onSuccess a callback with the scene when import succeeds
  67369. * @param onProgress a callback with a progress event for each file being loaded
  67370. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67371. * @param pluginExtension the extension used to determine the plugin
  67372. * @returns The loaded plugin
  67373. */
  67374. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67375. if (onSuccess === void 0) { onSuccess = null; }
  67376. if (onProgress === void 0) { onProgress = null; }
  67377. if (onError === void 0) { onError = null; }
  67378. if (pluginExtension === void 0) { pluginExtension = null; }
  67379. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67380. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67381. return null;
  67382. }
  67383. var loadingToken = {};
  67384. scene._addPendingData(loadingToken);
  67385. var disposeHandler = function () {
  67386. scene._removePendingData(loadingToken);
  67387. };
  67388. var errorHandler = function (message, exception) {
  67389. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67390. if (onError) {
  67391. onError(scene, errorMessage, exception);
  67392. }
  67393. else {
  67394. BABYLON.Tools.Error(errorMessage);
  67395. // should the exception be thrown?
  67396. }
  67397. disposeHandler();
  67398. };
  67399. var progressHandler = onProgress ? function (event) {
  67400. try {
  67401. onProgress(event);
  67402. }
  67403. catch (e) {
  67404. errorHandler("Error in onProgress callback", e);
  67405. }
  67406. } : undefined;
  67407. var successHandler = function (assets) {
  67408. if (onSuccess) {
  67409. try {
  67410. onSuccess(assets);
  67411. }
  67412. catch (e) {
  67413. errorHandler("Error in onSuccess callback", e);
  67414. }
  67415. }
  67416. scene._removePendingData(loadingToken);
  67417. };
  67418. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67419. if (plugin.loadAssetContainer) {
  67420. var syncedPlugin = plugin;
  67421. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67422. if (!assetContainer) {
  67423. return;
  67424. }
  67425. scene.loadingPluginName = plugin.name;
  67426. successHandler(assetContainer);
  67427. }
  67428. else if (plugin.loadAssetContainerAsync) {
  67429. var asyncedPlugin = plugin;
  67430. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67431. scene.loadingPluginName = plugin.name;
  67432. successHandler(assetContainer);
  67433. }).catch(function (error) {
  67434. errorHandler(error.message, error);
  67435. });
  67436. }
  67437. else {
  67438. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67439. }
  67440. if (SceneLoader.ShowLoadingScreen) {
  67441. scene.executeWhenReady(function () {
  67442. scene.getEngine().hideLoadingUI();
  67443. });
  67444. }
  67445. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67446. };
  67447. /**
  67448. * Load a scene into an asset container
  67449. * @param rootUrl a string that defines the root url for scene and resources
  67450. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67451. * @param scene is the instance of BABYLON.Scene to append to
  67452. * @param onProgress a callback with a progress event for each file being loaded
  67453. * @param pluginExtension the extension used to determine the plugin
  67454. * @returns The loaded asset container
  67455. */
  67456. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67457. if (onProgress === void 0) { onProgress = null; }
  67458. if (pluginExtension === void 0) { pluginExtension = null; }
  67459. return new Promise(function (resolve, reject) {
  67460. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67461. resolve(assetContainer);
  67462. }, onProgress, function (scene, message, exception) {
  67463. reject(exception || new Error(message));
  67464. }, pluginExtension);
  67465. });
  67466. };
  67467. // Flags
  67468. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67469. SceneLoader._ShowLoadingScreen = true;
  67470. SceneLoader._CleanBoneMatrixWeights = false;
  67471. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67472. // Members
  67473. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67474. SceneLoader._registeredPlugins = {};
  67475. return SceneLoader;
  67476. }());
  67477. BABYLON.SceneLoader = SceneLoader;
  67478. ;
  67479. })(BABYLON || (BABYLON = {}));
  67480. //# sourceMappingURL=babylon.sceneLoader.js.map
  67481. var BABYLON;
  67482. (function (BABYLON) {
  67483. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67484. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67485. var parsedMaterial = parsedData.materials[index];
  67486. if (parsedMaterial.id === id) {
  67487. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67488. }
  67489. }
  67490. return null;
  67491. };
  67492. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67493. for (var i in names) {
  67494. if (mesh.name === names[i]) {
  67495. hierarchyIds.push(mesh.id);
  67496. return true;
  67497. }
  67498. }
  67499. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67500. hierarchyIds.push(mesh.id);
  67501. return true;
  67502. }
  67503. return false;
  67504. };
  67505. var logOperation = function (operation, producer) {
  67506. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67507. };
  67508. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67509. if (addToScene === void 0) { addToScene = false; }
  67510. var container = new BABYLON.AssetContainer(scene);
  67511. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67512. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67513. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67514. // and avoid problems with multiple concurrent .babylon loads.
  67515. var log = "importScene has failed JSON parse";
  67516. try {
  67517. var parsedData = JSON.parse(data);
  67518. log = "";
  67519. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67520. var index;
  67521. var cache;
  67522. // Lights
  67523. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67524. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67525. var parsedLight = parsedData.lights[index];
  67526. var light = BABYLON.Light.Parse(parsedLight, scene);
  67527. if (light) {
  67528. container.lights.push(light);
  67529. log += (index === 0 ? "\n\tLights:" : "");
  67530. log += "\n\t\t" + light.toString(fullDetails);
  67531. }
  67532. }
  67533. }
  67534. // Animations
  67535. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67536. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67537. var parsedAnimation = parsedData.animations[index];
  67538. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67539. scene.animations.push(animation);
  67540. container.animations.push(animation);
  67541. log += (index === 0 ? "\n\tAnimations:" : "");
  67542. log += "\n\t\t" + animation.toString(fullDetails);
  67543. }
  67544. }
  67545. // Materials
  67546. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67547. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67548. var parsedMaterial = parsedData.materials[index];
  67549. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67550. container.materials.push(mat);
  67551. log += (index === 0 ? "\n\tMaterials:" : "");
  67552. log += "\n\t\t" + mat.toString(fullDetails);
  67553. }
  67554. }
  67555. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67556. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67557. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67558. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67559. container.multiMaterials.push(mmat);
  67560. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67561. log += "\n\t\t" + mmat.toString(fullDetails);
  67562. }
  67563. }
  67564. // Morph targets
  67565. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67566. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67567. var managerData = _a[_i];
  67568. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67569. }
  67570. }
  67571. // Skeletons
  67572. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67573. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67574. var parsedSkeleton = parsedData.skeletons[index];
  67575. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67576. container.skeletons.push(skeleton);
  67577. log += (index === 0 ? "\n\tSkeletons:" : "");
  67578. log += "\n\t\t" + skeleton.toString(fullDetails);
  67579. }
  67580. }
  67581. // Geometries
  67582. var geometries = parsedData.geometries;
  67583. if (geometries !== undefined && geometries !== null) {
  67584. var addedGeometry = new Array();
  67585. // Boxes
  67586. var boxes = geometries.boxes;
  67587. if (boxes !== undefined && boxes !== null) {
  67588. for (index = 0, cache = boxes.length; index < cache; index++) {
  67589. var parsedBox = boxes[index];
  67590. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67591. }
  67592. }
  67593. // Spheres
  67594. var spheres = geometries.spheres;
  67595. if (spheres !== undefined && spheres !== null) {
  67596. for (index = 0, cache = spheres.length; index < cache; index++) {
  67597. var parsedSphere = spheres[index];
  67598. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67599. }
  67600. }
  67601. // Cylinders
  67602. var cylinders = geometries.cylinders;
  67603. if (cylinders !== undefined && cylinders !== null) {
  67604. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67605. var parsedCylinder = cylinders[index];
  67606. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67607. }
  67608. }
  67609. // Toruses
  67610. var toruses = geometries.toruses;
  67611. if (toruses !== undefined && toruses !== null) {
  67612. for (index = 0, cache = toruses.length; index < cache; index++) {
  67613. var parsedTorus = toruses[index];
  67614. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67615. }
  67616. }
  67617. // Grounds
  67618. var grounds = geometries.grounds;
  67619. if (grounds !== undefined && grounds !== null) {
  67620. for (index = 0, cache = grounds.length; index < cache; index++) {
  67621. var parsedGround = grounds[index];
  67622. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67623. }
  67624. }
  67625. // Planes
  67626. var planes = geometries.planes;
  67627. if (planes !== undefined && planes !== null) {
  67628. for (index = 0, cache = planes.length; index < cache; index++) {
  67629. var parsedPlane = planes[index];
  67630. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67631. }
  67632. }
  67633. // TorusKnots
  67634. var torusKnots = geometries.torusKnots;
  67635. if (torusKnots !== undefined && torusKnots !== null) {
  67636. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67637. var parsedTorusKnot = torusKnots[index];
  67638. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67639. }
  67640. }
  67641. // VertexData
  67642. var vertexData = geometries.vertexData;
  67643. if (vertexData !== undefined && vertexData !== null) {
  67644. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67645. var parsedVertexData = vertexData[index];
  67646. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67647. }
  67648. }
  67649. addedGeometry.forEach(function (g) {
  67650. if (g) {
  67651. container.geometries.push(g);
  67652. }
  67653. });
  67654. }
  67655. // Transform nodes
  67656. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67657. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67658. var parsedTransformNode = parsedData.transformNodes[index];
  67659. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67660. container.transformNodes.push(node);
  67661. }
  67662. }
  67663. // Meshes
  67664. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67665. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67666. var parsedMesh = parsedData.meshes[index];
  67667. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67668. container.meshes.push(mesh);
  67669. log += (index === 0 ? "\n\tMeshes:" : "");
  67670. log += "\n\t\t" + mesh.toString(fullDetails);
  67671. }
  67672. }
  67673. // Cameras
  67674. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67675. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67676. var parsedCamera = parsedData.cameras[index];
  67677. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67678. container.cameras.push(camera);
  67679. log += (index === 0 ? "\n\tCameras:" : "");
  67680. log += "\n\t\t" + camera.toString(fullDetails);
  67681. }
  67682. }
  67683. // Browsing all the graph to connect the dots
  67684. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67685. var camera = scene.cameras[index];
  67686. if (camera._waitingParentId) {
  67687. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67688. camera._waitingParentId = null;
  67689. }
  67690. }
  67691. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67692. var light_1 = scene.lights[index];
  67693. if (light_1 && light_1._waitingParentId) {
  67694. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67695. light_1._waitingParentId = null;
  67696. }
  67697. }
  67698. // Sounds
  67699. // TODO: add sound
  67700. var loadedSounds = [];
  67701. var loadedSound;
  67702. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67703. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67704. var parsedSound = parsedData.sounds[index];
  67705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67706. if (!parsedSound.url)
  67707. parsedSound.url = parsedSound.name;
  67708. if (!loadedSounds[parsedSound.url]) {
  67709. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67710. loadedSounds[parsedSound.url] = loadedSound;
  67711. container.sounds.push(loadedSound);
  67712. }
  67713. else {
  67714. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67715. }
  67716. }
  67717. else {
  67718. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67719. }
  67720. }
  67721. }
  67722. loadedSounds = [];
  67723. // Connect parents & children and parse actions
  67724. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67725. var transformNode = scene.transformNodes[index];
  67726. if (transformNode._waitingParentId) {
  67727. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67728. transformNode._waitingParentId = null;
  67729. }
  67730. }
  67731. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67732. var mesh = scene.meshes[index];
  67733. if (mesh._waitingParentId) {
  67734. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67735. mesh._waitingParentId = null;
  67736. }
  67737. if (mesh._waitingActions) {
  67738. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67739. mesh._waitingActions = null;
  67740. }
  67741. }
  67742. // freeze world matrix application
  67743. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67744. var currentMesh = scene.meshes[index];
  67745. if (currentMesh._waitingFreezeWorldMatrix) {
  67746. currentMesh.freezeWorldMatrix();
  67747. currentMesh._waitingFreezeWorldMatrix = null;
  67748. }
  67749. else {
  67750. currentMesh.computeWorldMatrix(true);
  67751. }
  67752. }
  67753. // Particles Systems
  67754. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67755. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67756. var parsedParticleSystem = parsedData.particleSystems[index];
  67757. if (parsedParticleSystem.activeParticleCount) {
  67758. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67759. container.particleSystems.push(ps);
  67760. }
  67761. else {
  67762. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67763. container.particleSystems.push(ps);
  67764. }
  67765. }
  67766. }
  67767. // Lens flares
  67768. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67769. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67770. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67771. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67772. container.lensFlareSystems.push(lf);
  67773. }
  67774. }
  67775. // Shadows
  67776. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67777. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67778. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67779. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67780. container.shadowGenerators.push(sg);
  67781. }
  67782. }
  67783. // Lights exclusions / inclusions
  67784. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67785. var light_2 = scene.lights[index];
  67786. // Excluded check
  67787. if (light_2._excludedMeshesIds.length > 0) {
  67788. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67789. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67790. if (excludedMesh) {
  67791. light_2.excludedMeshes.push(excludedMesh);
  67792. }
  67793. }
  67794. light_2._excludedMeshesIds = [];
  67795. }
  67796. // Included check
  67797. if (light_2._includedOnlyMeshesIds.length > 0) {
  67798. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67799. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67800. if (includedOnlyMesh) {
  67801. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67802. }
  67803. }
  67804. light_2._includedOnlyMeshesIds = [];
  67805. }
  67806. }
  67807. // Effect layers
  67808. if (parsedData.effectLayers) {
  67809. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67810. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67811. container.effectLayers.push(effectLayer);
  67812. }
  67813. }
  67814. // Actions (scene)
  67815. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67816. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67817. }
  67818. if (!addToScene) {
  67819. container.removeAllFromScene();
  67820. }
  67821. }
  67822. catch (err) {
  67823. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67824. if (onError) {
  67825. onError(msg, err);
  67826. }
  67827. else {
  67828. BABYLON.Tools.Log(msg);
  67829. throw err;
  67830. }
  67831. }
  67832. finally {
  67833. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67834. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67835. }
  67836. }
  67837. return container;
  67838. };
  67839. BABYLON.SceneLoader.RegisterPlugin({
  67840. name: "babylon.js",
  67841. extensions: ".babylon",
  67842. canDirectLoad: function (data) {
  67843. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67844. return true;
  67845. }
  67846. return false;
  67847. },
  67848. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67849. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67850. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67851. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67852. // and avoid problems with multiple concurrent .babylon loads.
  67853. var log = "importMesh has failed JSON parse";
  67854. try {
  67855. var parsedData = JSON.parse(data);
  67856. log = "";
  67857. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67858. if (!meshesNames) {
  67859. meshesNames = null;
  67860. }
  67861. else if (!Array.isArray(meshesNames)) {
  67862. meshesNames = [meshesNames];
  67863. }
  67864. var hierarchyIds = new Array();
  67865. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67866. var loadedSkeletonsIds = [];
  67867. var loadedMaterialsIds = [];
  67868. var index;
  67869. var cache;
  67870. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67871. var parsedMesh = parsedData.meshes[index];
  67872. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67873. if (meshesNames !== null) {
  67874. // Remove found mesh name from list.
  67875. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67876. }
  67877. //Geometry?
  67878. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67879. //does the file contain geometries?
  67880. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67881. //find the correct geometry and add it to the scene
  67882. var found = false;
  67883. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67884. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67885. return;
  67886. }
  67887. else {
  67888. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67889. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67890. switch (geometryType) {
  67891. case "boxes":
  67892. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67893. break;
  67894. case "spheres":
  67895. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67896. break;
  67897. case "cylinders":
  67898. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67899. break;
  67900. case "toruses":
  67901. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67902. break;
  67903. case "grounds":
  67904. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67905. break;
  67906. case "planes":
  67907. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67908. break;
  67909. case "torusKnots":
  67910. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67911. break;
  67912. case "vertexData":
  67913. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67914. break;
  67915. }
  67916. found = true;
  67917. }
  67918. });
  67919. }
  67920. });
  67921. if (found === false) {
  67922. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67923. }
  67924. }
  67925. }
  67926. // Material ?
  67927. if (parsedMesh.materialId) {
  67928. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67929. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67930. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67931. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67932. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67933. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67934. var subMatId = parsedMultiMaterial.materials[matIndex];
  67935. loadedMaterialsIds.push(subMatId);
  67936. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67937. if (mat) {
  67938. log += "\n\tMaterial " + mat.toString(fullDetails);
  67939. }
  67940. }
  67941. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67942. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67943. if (mmat) {
  67944. materialFound = true;
  67945. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67946. }
  67947. break;
  67948. }
  67949. }
  67950. }
  67951. if (materialFound === false) {
  67952. loadedMaterialsIds.push(parsedMesh.materialId);
  67953. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67954. if (!mat) {
  67955. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67956. }
  67957. else {
  67958. log += "\n\tMaterial " + mat.toString(fullDetails);
  67959. }
  67960. }
  67961. }
  67962. // Skeleton ?
  67963. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67964. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67965. if (skeletonAlreadyLoaded === false) {
  67966. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67967. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67968. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67969. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67970. skeletons.push(skeleton);
  67971. loadedSkeletonsIds.push(parsedSkeleton.id);
  67972. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67973. }
  67974. }
  67975. }
  67976. }
  67977. // Morph targets ?
  67978. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67979. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67980. var managerData = _a[_i];
  67981. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67982. }
  67983. }
  67984. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67985. meshes.push(mesh);
  67986. log += "\n\tMesh " + mesh.toString(fullDetails);
  67987. }
  67988. }
  67989. // Connecting parents
  67990. var currentMesh;
  67991. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67992. currentMesh = scene.meshes[index];
  67993. if (currentMesh._waitingParentId) {
  67994. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67995. currentMesh._waitingParentId = null;
  67996. }
  67997. }
  67998. // freeze and compute world matrix application
  67999. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68000. currentMesh = scene.meshes[index];
  68001. if (currentMesh._waitingFreezeWorldMatrix) {
  68002. currentMesh.freezeWorldMatrix();
  68003. currentMesh._waitingFreezeWorldMatrix = null;
  68004. }
  68005. else {
  68006. currentMesh.computeWorldMatrix(true);
  68007. }
  68008. }
  68009. }
  68010. // Particles
  68011. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68012. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68013. var parsedParticleSystem = parsedData.particleSystems[index];
  68014. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68015. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68016. }
  68017. }
  68018. }
  68019. return true;
  68020. }
  68021. catch (err) {
  68022. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68023. if (onError) {
  68024. onError(msg, err);
  68025. }
  68026. else {
  68027. BABYLON.Tools.Log(msg);
  68028. throw err;
  68029. }
  68030. }
  68031. finally {
  68032. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68033. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68034. }
  68035. }
  68036. return false;
  68037. },
  68038. load: function (scene, data, rootUrl, onError) {
  68039. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68040. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68041. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68042. // and avoid problems with multiple concurrent .babylon loads.
  68043. var log = "importScene has failed JSON parse";
  68044. try {
  68045. var parsedData = JSON.parse(data);
  68046. log = "";
  68047. // Scene
  68048. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68049. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68050. }
  68051. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68052. scene.autoClear = parsedData.autoClear;
  68053. }
  68054. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68055. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68056. }
  68057. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68058. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68059. }
  68060. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68061. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68062. }
  68063. // Fog
  68064. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68065. scene.fogMode = parsedData.fogMode;
  68066. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68067. scene.fogStart = parsedData.fogStart;
  68068. scene.fogEnd = parsedData.fogEnd;
  68069. scene.fogDensity = parsedData.fogDensity;
  68070. log += "\tFog mode for scene: ";
  68071. switch (scene.fogMode) {
  68072. // getters not compiling, so using hardcoded
  68073. case 1:
  68074. log += "exp\n";
  68075. break;
  68076. case 2:
  68077. log += "exp2\n";
  68078. break;
  68079. case 3:
  68080. log += "linear\n";
  68081. break;
  68082. }
  68083. }
  68084. //Physics
  68085. if (parsedData.physicsEnabled) {
  68086. var physicsPlugin;
  68087. if (parsedData.physicsEngine === "cannon") {
  68088. physicsPlugin = new BABYLON.CannonJSPlugin();
  68089. }
  68090. else if (parsedData.physicsEngine === "oimo") {
  68091. physicsPlugin = new BABYLON.OimoJSPlugin();
  68092. }
  68093. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68094. //else - default engine, which is currently oimo
  68095. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68096. scene.enablePhysics(physicsGravity, physicsPlugin);
  68097. }
  68098. // Metadata
  68099. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68100. scene.metadata = parsedData.metadata;
  68101. }
  68102. //collisions, if defined. otherwise, default is true
  68103. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68104. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68105. }
  68106. scene.workerCollisions = !!parsedData.workerCollisions;
  68107. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68108. if (!container) {
  68109. return false;
  68110. }
  68111. if (parsedData.autoAnimate) {
  68112. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68113. }
  68114. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68115. scene.setActiveCameraByID(parsedData.activeCameraID);
  68116. }
  68117. // Environment texture
  68118. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68119. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68120. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68121. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68122. if (parsedData.environmentTextureRotationY) {
  68123. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68124. }
  68125. scene.environmentTexture = hdrTexture;
  68126. }
  68127. else {
  68128. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68129. if (parsedData.environmentTextureRotationY) {
  68130. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68131. }
  68132. scene.environmentTexture = cubeTexture;
  68133. }
  68134. if (parsedData.createDefaultSkybox === true) {
  68135. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68136. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68137. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68138. }
  68139. }
  68140. // Finish
  68141. return true;
  68142. }
  68143. catch (err) {
  68144. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68145. if (onError) {
  68146. onError(msg, err);
  68147. }
  68148. else {
  68149. BABYLON.Tools.Log(msg);
  68150. throw err;
  68151. }
  68152. }
  68153. finally {
  68154. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68155. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68156. }
  68157. }
  68158. return false;
  68159. },
  68160. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68161. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68162. return container;
  68163. }
  68164. });
  68165. })(BABYLON || (BABYLON = {}));
  68166. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68167. var BABYLON;
  68168. (function (BABYLON) {
  68169. var FilesInput = /** @class */ (function () {
  68170. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68171. this.onProcessFileCallback = function () { return true; };
  68172. this._engine = engine;
  68173. this._currentScene = scene;
  68174. this._sceneLoadedCallback = sceneLoadedCallback;
  68175. this._progressCallback = progressCallback;
  68176. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68177. this._textureLoadingCallback = textureLoadingCallback;
  68178. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68179. this._onReloadCallback = onReloadCallback;
  68180. this._errorCallback = errorCallback;
  68181. }
  68182. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68183. var _this = this;
  68184. if (elementToMonitor) {
  68185. this._elementToMonitor = elementToMonitor;
  68186. this._dragEnterHandler = function (e) { _this.drag(e); };
  68187. this._dragOverHandler = function (e) { _this.drag(e); };
  68188. this._dropHandler = function (e) { _this.drop(e); };
  68189. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68190. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68191. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68192. }
  68193. };
  68194. FilesInput.prototype.dispose = function () {
  68195. if (!this._elementToMonitor) {
  68196. return;
  68197. }
  68198. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68199. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68200. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68201. };
  68202. FilesInput.prototype.renderFunction = function () {
  68203. if (this._additionalRenderLoopLogicCallback) {
  68204. this._additionalRenderLoopLogicCallback();
  68205. }
  68206. if (this._currentScene) {
  68207. if (this._textureLoadingCallback) {
  68208. var remaining = this._currentScene.getWaitingItemsCount();
  68209. if (remaining > 0) {
  68210. this._textureLoadingCallback(remaining);
  68211. }
  68212. }
  68213. this._currentScene.render();
  68214. }
  68215. };
  68216. FilesInput.prototype.drag = function (e) {
  68217. e.stopPropagation();
  68218. e.preventDefault();
  68219. };
  68220. FilesInput.prototype.drop = function (eventDrop) {
  68221. eventDrop.stopPropagation();
  68222. eventDrop.preventDefault();
  68223. this.loadFiles(eventDrop);
  68224. };
  68225. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68226. var _this = this;
  68227. var reader = folder.createReader();
  68228. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68229. reader.readEntries(function (entries) {
  68230. remaining.count += entries.length;
  68231. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68232. var entry = entries_1[_i];
  68233. if (entry.isFile) {
  68234. entry.file(function (file) {
  68235. file.correctName = relativePath + file.name;
  68236. files.push(file);
  68237. if (--remaining.count === 0) {
  68238. callback();
  68239. }
  68240. });
  68241. }
  68242. else if (entry.isDirectory) {
  68243. _this._traverseFolder(entry, files, remaining, callback);
  68244. }
  68245. }
  68246. if (--remaining.count) {
  68247. callback();
  68248. }
  68249. });
  68250. };
  68251. FilesInput.prototype._processFiles = function (files) {
  68252. for (var i = 0; i < files.length; i++) {
  68253. var name = files[i].correctName.toLowerCase();
  68254. var extension = name.split('.').pop();
  68255. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68256. continue;
  68257. }
  68258. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68259. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68260. this._sceneFileToLoad = files[i];
  68261. }
  68262. else {
  68263. FilesInput.FilesToLoad[name] = files[i];
  68264. }
  68265. }
  68266. };
  68267. FilesInput.prototype.loadFiles = function (event) {
  68268. var _this = this;
  68269. if (this._startingProcessingFilesCallback)
  68270. this._startingProcessingFilesCallback();
  68271. // Handling data transfer via drag'n'drop
  68272. if (event && event.dataTransfer && event.dataTransfer.files) {
  68273. this._filesToLoad = event.dataTransfer.files;
  68274. }
  68275. // Handling files from input files
  68276. if (event && event.target && event.target.files) {
  68277. this._filesToLoad = event.target.files;
  68278. }
  68279. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68280. var files_1 = new Array();
  68281. var folders = [];
  68282. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68283. for (var i = 0; i < this._filesToLoad.length; i++) {
  68284. var fileToLoad = this._filesToLoad[i];
  68285. var name_1 = fileToLoad.name.toLowerCase();
  68286. var entry = void 0;
  68287. fileToLoad.correctName = name_1;
  68288. if (items) {
  68289. var item = items[i];
  68290. if (item.getAsEntry) {
  68291. entry = item.getAsEntry();
  68292. }
  68293. else if (item.webkitGetAsEntry) {
  68294. entry = item.webkitGetAsEntry();
  68295. }
  68296. }
  68297. if (!entry) {
  68298. files_1.push(fileToLoad);
  68299. }
  68300. else {
  68301. if (entry.isDirectory) {
  68302. folders.push(entry);
  68303. }
  68304. else {
  68305. files_1.push(fileToLoad);
  68306. }
  68307. }
  68308. }
  68309. if (folders.length === 0) {
  68310. this._processFiles(files_1);
  68311. this._processReload();
  68312. }
  68313. else {
  68314. var remaining = { count: folders.length };
  68315. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68316. var folder = folders_1[_i];
  68317. this._traverseFolder(folder, files_1, remaining, function () {
  68318. _this._processFiles(files_1);
  68319. if (remaining.count === 0) {
  68320. _this._processReload();
  68321. }
  68322. });
  68323. }
  68324. }
  68325. }
  68326. };
  68327. FilesInput.prototype._processReload = function () {
  68328. if (this._onReloadCallback) {
  68329. this._onReloadCallback(this._sceneFileToLoad);
  68330. }
  68331. else {
  68332. this.reload();
  68333. }
  68334. };
  68335. FilesInput.prototype.reload = function () {
  68336. var _this = this;
  68337. // If a scene file has been provided
  68338. if (this._sceneFileToLoad) {
  68339. if (this._currentScene) {
  68340. if (BABYLON.Tools.errorsCount > 0) {
  68341. BABYLON.Tools.ClearLogCache();
  68342. }
  68343. this._engine.stopRenderLoop();
  68344. this._currentScene.dispose();
  68345. }
  68346. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68347. if (_this._progressCallback) {
  68348. _this._progressCallback(progress);
  68349. }
  68350. }).then(function (scene) {
  68351. _this._currentScene = scene;
  68352. if (_this._sceneLoadedCallback) {
  68353. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68354. }
  68355. // Wait for textures and shaders to be ready
  68356. _this._currentScene.executeWhenReady(function () {
  68357. _this._engine.runRenderLoop(function () {
  68358. _this.renderFunction();
  68359. });
  68360. });
  68361. }).catch(function (error) {
  68362. if (_this._errorCallback) {
  68363. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68364. }
  68365. });
  68366. }
  68367. else {
  68368. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68369. }
  68370. };
  68371. FilesInput.FilesToLoad = {};
  68372. return FilesInput;
  68373. }());
  68374. BABYLON.FilesInput = FilesInput;
  68375. })(BABYLON || (BABYLON = {}));
  68376. //# sourceMappingURL=babylon.filesInput.js.map
  68377. var BABYLON;
  68378. (function (BABYLON) {
  68379. /**
  68380. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68381. * The underlying implementation relies on an associative array to ensure the best performances.
  68382. * The value can be anything including 'null' but except 'undefined'
  68383. */
  68384. var StringDictionary = /** @class */ (function () {
  68385. function StringDictionary() {
  68386. this._count = 0;
  68387. this._data = {};
  68388. }
  68389. /**
  68390. * This will clear this dictionary and copy the content from the 'source' one.
  68391. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68392. * @param source the dictionary to take the content from and copy to this dictionary
  68393. */
  68394. StringDictionary.prototype.copyFrom = function (source) {
  68395. var _this = this;
  68396. this.clear();
  68397. source.forEach(function (t, v) { return _this.add(t, v); });
  68398. };
  68399. /**
  68400. * Get a value based from its key
  68401. * @param key the given key to get the matching value from
  68402. * @return the value if found, otherwise undefined is returned
  68403. */
  68404. StringDictionary.prototype.get = function (key) {
  68405. var val = this._data[key];
  68406. if (val !== undefined) {
  68407. return val;
  68408. }
  68409. return undefined;
  68410. };
  68411. /**
  68412. * Get a value from its key or add it if it doesn't exist.
  68413. * This method will ensure you that a given key/data will be present in the dictionary.
  68414. * @param key the given key to get the matching value from
  68415. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68416. * The factory will only be invoked if there's no data for the given key.
  68417. * @return the value corresponding to the key.
  68418. */
  68419. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68420. var val = this.get(key);
  68421. if (val !== undefined) {
  68422. return val;
  68423. }
  68424. val = factory(key);
  68425. if (val) {
  68426. this.add(key, val);
  68427. }
  68428. return val;
  68429. };
  68430. /**
  68431. * Get a value from its key if present in the dictionary otherwise add it
  68432. * @param key the key to get the value from
  68433. * @param val if there's no such key/value pair in the dictionary add it with this value
  68434. * @return the value corresponding to the key
  68435. */
  68436. StringDictionary.prototype.getOrAdd = function (key, val) {
  68437. var curVal = this.get(key);
  68438. if (curVal !== undefined) {
  68439. return curVal;
  68440. }
  68441. this.add(key, val);
  68442. return val;
  68443. };
  68444. /**
  68445. * Check if there's a given key in the dictionary
  68446. * @param key the key to check for
  68447. * @return true if the key is present, false otherwise
  68448. */
  68449. StringDictionary.prototype.contains = function (key) {
  68450. return this._data[key] !== undefined;
  68451. };
  68452. /**
  68453. * Add a new key and its corresponding value
  68454. * @param key the key to add
  68455. * @param value the value corresponding to the key
  68456. * @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
  68457. */
  68458. StringDictionary.prototype.add = function (key, value) {
  68459. if (this._data[key] !== undefined) {
  68460. return false;
  68461. }
  68462. this._data[key] = value;
  68463. ++this._count;
  68464. return true;
  68465. };
  68466. StringDictionary.prototype.set = function (key, value) {
  68467. if (this._data[key] === undefined) {
  68468. return false;
  68469. }
  68470. this._data[key] = value;
  68471. return true;
  68472. };
  68473. /**
  68474. * Get the element of the given key and remove it from the dictionary
  68475. * @param key
  68476. */
  68477. StringDictionary.prototype.getAndRemove = function (key) {
  68478. var val = this.get(key);
  68479. if (val !== undefined) {
  68480. delete this._data[key];
  68481. --this._count;
  68482. return val;
  68483. }
  68484. return null;
  68485. };
  68486. /**
  68487. * Remove a key/value from the dictionary.
  68488. * @param key the key to remove
  68489. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68490. */
  68491. StringDictionary.prototype.remove = function (key) {
  68492. if (this.contains(key)) {
  68493. delete this._data[key];
  68494. --this._count;
  68495. return true;
  68496. }
  68497. return false;
  68498. };
  68499. /**
  68500. * Clear the whole content of the dictionary
  68501. */
  68502. StringDictionary.prototype.clear = function () {
  68503. this._data = {};
  68504. this._count = 0;
  68505. };
  68506. Object.defineProperty(StringDictionary.prototype, "count", {
  68507. get: function () {
  68508. return this._count;
  68509. },
  68510. enumerable: true,
  68511. configurable: true
  68512. });
  68513. /**
  68514. * Execute a callback on each key/val of the dictionary.
  68515. * Note that you can remove any element in this dictionary in the callback implementation
  68516. * @param callback the callback to execute on a given key/value pair
  68517. */
  68518. StringDictionary.prototype.forEach = function (callback) {
  68519. for (var cur in this._data) {
  68520. var val = this._data[cur];
  68521. callback(cur, val);
  68522. }
  68523. };
  68524. /**
  68525. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68526. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68527. * Note that you can remove any element in this dictionary in the callback implementation
  68528. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68529. */
  68530. StringDictionary.prototype.first = function (callback) {
  68531. for (var cur in this._data) {
  68532. var val = this._data[cur];
  68533. var res = callback(cur, val);
  68534. if (res) {
  68535. return res;
  68536. }
  68537. }
  68538. return null;
  68539. };
  68540. return StringDictionary;
  68541. }());
  68542. BABYLON.StringDictionary = StringDictionary;
  68543. })(BABYLON || (BABYLON = {}));
  68544. //# sourceMappingURL=babylon.stringDictionary.js.map
  68545. var BABYLON;
  68546. (function (BABYLON) {
  68547. var Tags = /** @class */ (function () {
  68548. function Tags() {
  68549. }
  68550. Tags.EnableFor = function (obj) {
  68551. obj._tags = obj._tags || {};
  68552. obj.hasTags = function () {
  68553. return Tags.HasTags(obj);
  68554. };
  68555. obj.addTags = function (tagsString) {
  68556. return Tags.AddTagsTo(obj, tagsString);
  68557. };
  68558. obj.removeTags = function (tagsString) {
  68559. return Tags.RemoveTagsFrom(obj, tagsString);
  68560. };
  68561. obj.matchesTagsQuery = function (tagsQuery) {
  68562. return Tags.MatchesQuery(obj, tagsQuery);
  68563. };
  68564. };
  68565. Tags.DisableFor = function (obj) {
  68566. delete obj._tags;
  68567. delete obj.hasTags;
  68568. delete obj.addTags;
  68569. delete obj.removeTags;
  68570. delete obj.matchesTagsQuery;
  68571. };
  68572. Tags.HasTags = function (obj) {
  68573. if (!obj._tags) {
  68574. return false;
  68575. }
  68576. return !BABYLON.Tools.IsEmpty(obj._tags);
  68577. };
  68578. Tags.GetTags = function (obj, asString) {
  68579. if (asString === void 0) { asString = true; }
  68580. if (!obj._tags) {
  68581. return null;
  68582. }
  68583. if (asString) {
  68584. var tagsArray = [];
  68585. for (var tag in obj._tags) {
  68586. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68587. tagsArray.push(tag);
  68588. }
  68589. }
  68590. return tagsArray.join(" ");
  68591. }
  68592. else {
  68593. return obj._tags;
  68594. }
  68595. };
  68596. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68597. // a tag cannot start with '||', '&&', and '!'
  68598. // it cannot contain whitespaces
  68599. Tags.AddTagsTo = function (obj, tagsString) {
  68600. if (!tagsString) {
  68601. return;
  68602. }
  68603. if (typeof tagsString !== "string") {
  68604. return;
  68605. }
  68606. var tags = tagsString.split(" ");
  68607. tags.forEach(function (tag, index, array) {
  68608. Tags._AddTagTo(obj, tag);
  68609. });
  68610. };
  68611. Tags._AddTagTo = function (obj, tag) {
  68612. tag = tag.trim();
  68613. if (tag === "" || tag === "true" || tag === "false") {
  68614. return;
  68615. }
  68616. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68617. return;
  68618. }
  68619. Tags.EnableFor(obj);
  68620. obj._tags[tag] = true;
  68621. };
  68622. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68623. if (!Tags.HasTags(obj)) {
  68624. return;
  68625. }
  68626. var tags = tagsString.split(" ");
  68627. for (var t in tags) {
  68628. Tags._RemoveTagFrom(obj, tags[t]);
  68629. }
  68630. };
  68631. Tags._RemoveTagFrom = function (obj, tag) {
  68632. delete obj._tags[tag];
  68633. };
  68634. Tags.MatchesQuery = function (obj, tagsQuery) {
  68635. if (tagsQuery === undefined) {
  68636. return true;
  68637. }
  68638. if (tagsQuery === "") {
  68639. return Tags.HasTags(obj);
  68640. }
  68641. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68642. };
  68643. return Tags;
  68644. }());
  68645. BABYLON.Tags = Tags;
  68646. })(BABYLON || (BABYLON = {}));
  68647. //# sourceMappingURL=babylon.tags.js.map
  68648. var BABYLON;
  68649. (function (BABYLON) {
  68650. /**
  68651. * Class used to evalaute queries containing `and` and `or` operators
  68652. */
  68653. var AndOrNotEvaluator = /** @class */ (function () {
  68654. function AndOrNotEvaluator() {
  68655. }
  68656. /**
  68657. * Evaluate a query
  68658. * @param query defines the query to evaluate
  68659. * @param evaluateCallback defines the callback used to filter result
  68660. * @returns true if the query matches
  68661. */
  68662. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68663. if (!query.match(/\([^\(\)]*\)/g)) {
  68664. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68665. }
  68666. else {
  68667. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68668. // remove parenthesis
  68669. r = r.slice(1, r.length - 1);
  68670. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68671. });
  68672. }
  68673. if (query === "true") {
  68674. return true;
  68675. }
  68676. if (query === "false") {
  68677. return false;
  68678. }
  68679. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68680. };
  68681. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68682. evaluateCallback = evaluateCallback || (function (r) {
  68683. return r === "true" ? true : false;
  68684. });
  68685. var result;
  68686. var or = parenthesisContent.split("||");
  68687. for (var i in or) {
  68688. if (or.hasOwnProperty(i)) {
  68689. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68690. var and = ori.split("&&");
  68691. if (and.length > 1) {
  68692. for (var j = 0; j < and.length; ++j) {
  68693. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68694. if (andj !== "true" && andj !== "false") {
  68695. if (andj[0] === "!") {
  68696. result = !evaluateCallback(andj.substring(1));
  68697. }
  68698. else {
  68699. result = evaluateCallback(andj);
  68700. }
  68701. }
  68702. else {
  68703. result = andj === "true" ? true : false;
  68704. }
  68705. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68706. ori = "false";
  68707. break;
  68708. }
  68709. }
  68710. }
  68711. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68712. result = true;
  68713. break;
  68714. }
  68715. // result equals false (or undefined)
  68716. if (ori !== "true" && ori !== "false") {
  68717. if (ori[0] === "!") {
  68718. result = !evaluateCallback(ori.substring(1));
  68719. }
  68720. else {
  68721. result = evaluateCallback(ori);
  68722. }
  68723. }
  68724. else {
  68725. result = ori === "true" ? true : false;
  68726. }
  68727. }
  68728. }
  68729. // the whole parenthesis scope is replaced by 'true' or 'false'
  68730. return result ? "true" : "false";
  68731. };
  68732. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68733. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68734. // remove whitespaces
  68735. r = r.replace(/[\s]/g, function () { return ""; });
  68736. return r.length % 2 ? "!" : "";
  68737. });
  68738. booleanString = booleanString.trim();
  68739. if (booleanString === "!true") {
  68740. booleanString = "false";
  68741. }
  68742. else if (booleanString === "!false") {
  68743. booleanString = "true";
  68744. }
  68745. return booleanString;
  68746. };
  68747. return AndOrNotEvaluator;
  68748. }());
  68749. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68750. })(BABYLON || (BABYLON = {}));
  68751. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68752. var BABYLON;
  68753. (function (BABYLON) {
  68754. /**
  68755. * Class used to enable access to IndexedDB
  68756. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68757. */
  68758. var Database = /** @class */ (function () {
  68759. /**
  68760. * Creates a new Database
  68761. * @param urlToScene defines the url to load the scene
  68762. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68763. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68764. */
  68765. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68766. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68767. var _this = this;
  68768. // Handling various flavors of prefixed version of IndexedDB
  68769. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68770. this.callbackManifestChecked = callbackManifestChecked;
  68771. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68772. this.db = null;
  68773. this._enableSceneOffline = false;
  68774. this._enableTexturesOffline = false;
  68775. this.manifestVersionFound = 0;
  68776. this.mustUpdateRessources = false;
  68777. this.hasReachedQuota = false;
  68778. if (!Database.IDBStorageEnabled) {
  68779. this.callbackManifestChecked(true);
  68780. }
  68781. else {
  68782. if (disableManifestCheck) {
  68783. this._enableSceneOffline = true;
  68784. this._enableTexturesOffline = true;
  68785. this.manifestVersionFound = 1;
  68786. BABYLON.Tools.SetImmediate(function () {
  68787. _this.callbackManifestChecked(true);
  68788. });
  68789. }
  68790. else {
  68791. this._checkManifestFile();
  68792. }
  68793. }
  68794. }
  68795. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68796. /**
  68797. * Gets a boolean indicating if scene must be saved in the database
  68798. */
  68799. get: function () {
  68800. return this._enableSceneOffline;
  68801. },
  68802. enumerable: true,
  68803. configurable: true
  68804. });
  68805. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68806. /**
  68807. * Gets a boolean indicating if textures must be saved in the database
  68808. */
  68809. get: function () {
  68810. return this._enableTexturesOffline;
  68811. },
  68812. enumerable: true,
  68813. configurable: true
  68814. });
  68815. Database.prototype._checkManifestFile = function () {
  68816. var _this = this;
  68817. var noManifestFile = function () {
  68818. _this._enableSceneOffline = false;
  68819. _this._enableTexturesOffline = false;
  68820. _this.callbackManifestChecked(false);
  68821. };
  68822. var timeStampUsed = false;
  68823. var manifestURL = this.currentSceneUrl + ".manifest";
  68824. var xhr = new XMLHttpRequest();
  68825. if (navigator.onLine) {
  68826. // Adding a timestamp to by-pass browsers' cache
  68827. timeStampUsed = true;
  68828. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68829. }
  68830. xhr.open("GET", manifestURL, true);
  68831. xhr.addEventListener("load", function () {
  68832. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68833. try {
  68834. var manifestFile = JSON.parse(xhr.response);
  68835. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68836. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68837. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68838. _this.manifestVersionFound = manifestFile.version;
  68839. }
  68840. if (_this.callbackManifestChecked) {
  68841. _this.callbackManifestChecked(true);
  68842. }
  68843. }
  68844. catch (ex) {
  68845. noManifestFile();
  68846. }
  68847. }
  68848. else {
  68849. noManifestFile();
  68850. }
  68851. }, false);
  68852. xhr.addEventListener("error", function (event) {
  68853. if (timeStampUsed) {
  68854. timeStampUsed = false;
  68855. // Let's retry without the timeStamp
  68856. // It could fail when coupled with HTML5 Offline API
  68857. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68858. xhr.open("GET", retryManifestURL, true);
  68859. xhr.send();
  68860. }
  68861. else {
  68862. noManifestFile();
  68863. }
  68864. }, false);
  68865. try {
  68866. xhr.send();
  68867. }
  68868. catch (ex) {
  68869. BABYLON.Tools.Error("Error on XHR send request.");
  68870. this.callbackManifestChecked(false);
  68871. }
  68872. };
  68873. /**
  68874. * Open the database and make it available
  68875. * @param successCallback defines the callback to call on success
  68876. * @param errorCallback defines the callback to call on error
  68877. */
  68878. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68879. var _this = this;
  68880. var handleError = function () {
  68881. _this.isSupported = false;
  68882. if (errorCallback)
  68883. errorCallback();
  68884. };
  68885. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68886. // Your browser doesn't support IndexedDB
  68887. this.isSupported = false;
  68888. if (errorCallback)
  68889. errorCallback();
  68890. }
  68891. else {
  68892. // If the DB hasn't been opened or created yet
  68893. if (!this.db) {
  68894. this.hasReachedQuota = false;
  68895. this.isSupported = true;
  68896. var request = this.idbFactory.open("babylonjs", 1);
  68897. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68898. request.onerror = function (event) {
  68899. handleError();
  68900. };
  68901. // executes when a version change transaction cannot complete due to other active transactions
  68902. request.onblocked = function (event) {
  68903. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68904. handleError();
  68905. };
  68906. // DB has been opened successfully
  68907. request.onsuccess = function (event) {
  68908. _this.db = request.result;
  68909. successCallback();
  68910. };
  68911. // Initialization of the DB. Creating Scenes & Textures stores
  68912. request.onupgradeneeded = function (event) {
  68913. _this.db = (event.target).result;
  68914. if (_this.db) {
  68915. try {
  68916. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68917. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68918. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68919. }
  68920. catch (ex) {
  68921. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68922. handleError();
  68923. }
  68924. }
  68925. };
  68926. }
  68927. // DB has already been created and opened
  68928. else {
  68929. if (successCallback)
  68930. successCallback();
  68931. }
  68932. }
  68933. };
  68934. /**
  68935. * Loads an image from the database
  68936. * @param url defines the url to load from
  68937. * @param image defines the target DOM image
  68938. */
  68939. Database.prototype.loadImageFromDB = function (url, image) {
  68940. var _this = this;
  68941. var completeURL = Database._ReturnFullUrlLocation(url);
  68942. var saveAndLoadImage = function () {
  68943. if (!_this.hasReachedQuota && _this.db !== null) {
  68944. // the texture is not yet in the DB, let's try to save it
  68945. _this._saveImageIntoDBAsync(completeURL, image);
  68946. }
  68947. // If the texture is not in the DB and we've reached the DB quota limit
  68948. // let's load it directly from the web
  68949. else {
  68950. image.src = url;
  68951. }
  68952. };
  68953. if (!this.mustUpdateRessources) {
  68954. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68955. }
  68956. // First time we're download the images or update requested in the manifest file by a version change
  68957. else {
  68958. saveAndLoadImage();
  68959. }
  68960. };
  68961. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68962. if (this.isSupported && this.db !== null) {
  68963. var texture;
  68964. var transaction = this.db.transaction(["textures"]);
  68965. transaction.onabort = function (event) {
  68966. image.src = url;
  68967. };
  68968. transaction.oncomplete = function (event) {
  68969. var blobTextureURL;
  68970. if (texture) {
  68971. var URL = window.URL || window.webkitURL;
  68972. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68973. image.onerror = function () {
  68974. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68975. image.src = url;
  68976. };
  68977. image.src = blobTextureURL;
  68978. }
  68979. else {
  68980. notInDBCallback();
  68981. }
  68982. };
  68983. var getRequest = transaction.objectStore("textures").get(url);
  68984. getRequest.onsuccess = function (event) {
  68985. texture = (event.target).result;
  68986. };
  68987. getRequest.onerror = function (event) {
  68988. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68989. image.src = url;
  68990. };
  68991. }
  68992. else {
  68993. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68994. image.src = url;
  68995. }
  68996. };
  68997. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68998. var _this = this;
  68999. if (this.isSupported) {
  69000. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69001. var generateBlobUrl = function () {
  69002. var blobTextureURL;
  69003. if (blob) {
  69004. var URL = window.URL || window.webkitURL;
  69005. try {
  69006. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69007. }
  69008. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69009. catch (ex) {
  69010. blobTextureURL = URL.createObjectURL(blob);
  69011. }
  69012. }
  69013. if (blobTextureURL) {
  69014. image.src = blobTextureURL;
  69015. }
  69016. };
  69017. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69018. var xhr = new XMLHttpRequest(), blob;
  69019. xhr.open("GET", url, true);
  69020. xhr.responseType = "blob";
  69021. xhr.addEventListener("load", function () {
  69022. if (xhr.status === 200 && _this.db) {
  69023. // Blob as response (XHR2)
  69024. blob = xhr.response;
  69025. var transaction = _this.db.transaction(["textures"], "readwrite");
  69026. // the transaction could abort because of a QuotaExceededError error
  69027. transaction.onabort = function (event) {
  69028. try {
  69029. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69030. var srcElement = (event.srcElement || event.target);
  69031. var error = srcElement.error;
  69032. if (error && error.name === "QuotaExceededError") {
  69033. _this.hasReachedQuota = true;
  69034. }
  69035. }
  69036. catch (ex) { }
  69037. generateBlobUrl();
  69038. };
  69039. transaction.oncomplete = function (event) {
  69040. generateBlobUrl();
  69041. };
  69042. var newTexture = { textureUrl: url, data: blob };
  69043. try {
  69044. // Put the blob into the dabase
  69045. var addRequest = transaction.objectStore("textures").put(newTexture);
  69046. addRequest.onsuccess = function (event) {
  69047. };
  69048. addRequest.onerror = function (event) {
  69049. generateBlobUrl();
  69050. };
  69051. }
  69052. catch (ex) {
  69053. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69054. if (ex.code === 25) {
  69055. Database.IsUASupportingBlobStorage = false;
  69056. }
  69057. image.src = url;
  69058. }
  69059. }
  69060. else {
  69061. image.src = url;
  69062. }
  69063. }, false);
  69064. xhr.addEventListener("error", function (event) {
  69065. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69066. image.src = url;
  69067. }, false);
  69068. xhr.send();
  69069. }
  69070. else {
  69071. image.src = url;
  69072. }
  69073. }
  69074. else {
  69075. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69076. image.src = url;
  69077. }
  69078. };
  69079. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69080. var _this = this;
  69081. var updateVersion = function () {
  69082. // the version is not yet in the DB or we need to update it
  69083. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69084. };
  69085. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69086. };
  69087. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69088. var _this = this;
  69089. if (this.isSupported && this.db) {
  69090. var version;
  69091. try {
  69092. var transaction = this.db.transaction(["versions"]);
  69093. transaction.oncomplete = function (event) {
  69094. if (version) {
  69095. // If the version in the JSON file is different from the version in DB
  69096. if (_this.manifestVersionFound !== version.data) {
  69097. _this.mustUpdateRessources = true;
  69098. updateInDBCallback();
  69099. }
  69100. else {
  69101. callback(version.data);
  69102. }
  69103. }
  69104. // version was not found in DB
  69105. else {
  69106. _this.mustUpdateRessources = true;
  69107. updateInDBCallback();
  69108. }
  69109. };
  69110. transaction.onabort = function (event) {
  69111. callback(-1);
  69112. };
  69113. var getRequest = transaction.objectStore("versions").get(url);
  69114. getRequest.onsuccess = function (event) {
  69115. version = (event.target).result;
  69116. };
  69117. getRequest.onerror = function (event) {
  69118. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69119. callback(-1);
  69120. };
  69121. }
  69122. catch (ex) {
  69123. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69124. callback(-1);
  69125. }
  69126. }
  69127. else {
  69128. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69129. callback(-1);
  69130. }
  69131. };
  69132. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69133. var _this = this;
  69134. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69135. try {
  69136. // Open a transaction to the database
  69137. var transaction = this.db.transaction(["versions"], "readwrite");
  69138. // the transaction could abort because of a QuotaExceededError error
  69139. transaction.onabort = function (event) {
  69140. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69141. var error = event.srcElement['error'];
  69142. if (error && error.name === "QuotaExceededError") {
  69143. _this.hasReachedQuota = true;
  69144. }
  69145. }
  69146. catch (ex) { }
  69147. callback(-1);
  69148. };
  69149. transaction.oncomplete = function (event) {
  69150. callback(_this.manifestVersionFound);
  69151. };
  69152. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69153. // Put the scene into the database
  69154. var addRequest = transaction.objectStore("versions").put(newVersion);
  69155. addRequest.onsuccess = function (event) {
  69156. };
  69157. addRequest.onerror = function (event) {
  69158. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69159. };
  69160. }
  69161. catch (ex) {
  69162. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69163. callback(-1);
  69164. }
  69165. }
  69166. else {
  69167. callback(-1);
  69168. }
  69169. };
  69170. /**
  69171. * Loads a file from database
  69172. * @param url defines the URL to load from
  69173. * @param sceneLoaded defines a callback to call on success
  69174. * @param progressCallBack defines a callback to call when progress changed
  69175. * @param errorCallback defines a callback to call on error
  69176. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69177. */
  69178. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69179. var _this = this;
  69180. var completeUrl = Database._ReturnFullUrlLocation(url);
  69181. var saveAndLoadFile = function () {
  69182. // the scene is not yet in the DB, let's try to save it
  69183. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69184. };
  69185. this._checkVersionFromDB(completeUrl, function (version) {
  69186. if (version !== -1) {
  69187. if (!_this.mustUpdateRessources) {
  69188. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69189. }
  69190. else {
  69191. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69192. }
  69193. }
  69194. else {
  69195. if (errorCallback) {
  69196. errorCallback();
  69197. }
  69198. }
  69199. });
  69200. };
  69201. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69202. if (this.isSupported && this.db) {
  69203. var targetStore;
  69204. if (url.indexOf(".babylon") !== -1) {
  69205. targetStore = "scenes";
  69206. }
  69207. else {
  69208. targetStore = "textures";
  69209. }
  69210. var file;
  69211. var transaction = this.db.transaction([targetStore]);
  69212. transaction.oncomplete = function (event) {
  69213. if (file) {
  69214. callback(file.data);
  69215. }
  69216. // file was not found in DB
  69217. else {
  69218. notInDBCallback();
  69219. }
  69220. };
  69221. transaction.onabort = function (event) {
  69222. notInDBCallback();
  69223. };
  69224. var getRequest = transaction.objectStore(targetStore).get(url);
  69225. getRequest.onsuccess = function (event) {
  69226. file = (event.target).result;
  69227. };
  69228. getRequest.onerror = function (event) {
  69229. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69230. notInDBCallback();
  69231. };
  69232. }
  69233. else {
  69234. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69235. callback();
  69236. }
  69237. };
  69238. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69239. var _this = this;
  69240. if (this.isSupported) {
  69241. var targetStore;
  69242. if (url.indexOf(".babylon") !== -1) {
  69243. targetStore = "scenes";
  69244. }
  69245. else {
  69246. targetStore = "textures";
  69247. }
  69248. // Create XHR
  69249. var xhr = new XMLHttpRequest();
  69250. var fileData;
  69251. xhr.open("GET", url, true);
  69252. if (useArrayBuffer) {
  69253. xhr.responseType = "arraybuffer";
  69254. }
  69255. if (progressCallback) {
  69256. xhr.onprogress = progressCallback;
  69257. }
  69258. xhr.addEventListener("load", function () {
  69259. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69260. // Blob as response (XHR2)
  69261. //fileData = xhr.responseText;
  69262. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69263. if (!_this.hasReachedQuota && _this.db) {
  69264. // Open a transaction to the database
  69265. var transaction = _this.db.transaction([targetStore], "readwrite");
  69266. // the transaction could abort because of a QuotaExceededError error
  69267. transaction.onabort = function (event) {
  69268. try {
  69269. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69270. var error = event.srcElement['error'];
  69271. if (error && error.name === "QuotaExceededError") {
  69272. _this.hasReachedQuota = true;
  69273. }
  69274. }
  69275. catch (ex) { }
  69276. callback(fileData);
  69277. };
  69278. transaction.oncomplete = function (event) {
  69279. callback(fileData);
  69280. };
  69281. var newFile;
  69282. if (targetStore === "scenes") {
  69283. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69284. }
  69285. else {
  69286. newFile = { textureUrl: url, data: fileData };
  69287. }
  69288. try {
  69289. // Put the scene into the database
  69290. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69291. addRequest.onsuccess = function (event) {
  69292. };
  69293. addRequest.onerror = function (event) {
  69294. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69295. };
  69296. }
  69297. catch (ex) {
  69298. callback(fileData);
  69299. }
  69300. }
  69301. else {
  69302. callback(fileData);
  69303. }
  69304. }
  69305. else {
  69306. callback();
  69307. }
  69308. }, false);
  69309. xhr.addEventListener("error", function (event) {
  69310. BABYLON.Tools.Error("error on XHR request.");
  69311. callback();
  69312. }, false);
  69313. xhr.send();
  69314. }
  69315. else {
  69316. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69317. callback();
  69318. }
  69319. };
  69320. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69321. Database.IsUASupportingBlobStorage = true;
  69322. /** Gets a boolean indicating if Database storate is enabled */
  69323. Database.IDBStorageEnabled = true;
  69324. Database._ParseURL = function (url) {
  69325. var a = document.createElement('a');
  69326. a.href = url;
  69327. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69328. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69329. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69330. return absLocation;
  69331. };
  69332. Database._ReturnFullUrlLocation = function (url) {
  69333. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69334. return (Database._ParseURL(window.location.href) + url);
  69335. }
  69336. else {
  69337. return url;
  69338. }
  69339. };
  69340. return Database;
  69341. }());
  69342. BABYLON.Database = Database;
  69343. })(BABYLON || (BABYLON = {}));
  69344. //# sourceMappingURL=babylon.database.js.map
  69345. var BABYLON;
  69346. (function (BABYLON) {
  69347. var FresnelParameters = /** @class */ (function () {
  69348. function FresnelParameters() {
  69349. this._isEnabled = true;
  69350. this.leftColor = BABYLON.Color3.White();
  69351. this.rightColor = BABYLON.Color3.Black();
  69352. this.bias = 0;
  69353. this.power = 1;
  69354. }
  69355. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69356. get: function () {
  69357. return this._isEnabled;
  69358. },
  69359. set: function (value) {
  69360. if (this._isEnabled === value) {
  69361. return;
  69362. }
  69363. this._isEnabled = value;
  69364. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69365. },
  69366. enumerable: true,
  69367. configurable: true
  69368. });
  69369. FresnelParameters.prototype.clone = function () {
  69370. var newFresnelParameters = new FresnelParameters();
  69371. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69372. return newFresnelParameters;
  69373. };
  69374. FresnelParameters.prototype.serialize = function () {
  69375. var serializationObject = {};
  69376. serializationObject.isEnabled = this.isEnabled;
  69377. serializationObject.leftColor = this.leftColor.asArray();
  69378. serializationObject.rightColor = this.rightColor.asArray();
  69379. serializationObject.bias = this.bias;
  69380. serializationObject.power = this.power;
  69381. return serializationObject;
  69382. };
  69383. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69384. var fresnelParameters = new FresnelParameters();
  69385. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69386. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69387. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69388. fresnelParameters.bias = parsedFresnelParameters.bias;
  69389. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69390. return fresnelParameters;
  69391. };
  69392. return FresnelParameters;
  69393. }());
  69394. BABYLON.FresnelParameters = FresnelParameters;
  69395. })(BABYLON || (BABYLON = {}));
  69396. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69397. var BABYLON;
  69398. (function (BABYLON) {
  69399. var MultiMaterial = /** @class */ (function (_super) {
  69400. __extends(MultiMaterial, _super);
  69401. function MultiMaterial(name, scene) {
  69402. var _this = _super.call(this, name, scene, true) || this;
  69403. scene.multiMaterials.push(_this);
  69404. _this.subMaterials = new Array();
  69405. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69406. return _this;
  69407. }
  69408. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69409. get: function () {
  69410. return this._subMaterials;
  69411. },
  69412. set: function (value) {
  69413. this._subMaterials = value;
  69414. this._hookArray(value);
  69415. },
  69416. enumerable: true,
  69417. configurable: true
  69418. });
  69419. MultiMaterial.prototype._hookArray = function (array) {
  69420. var _this = this;
  69421. var oldPush = array.push;
  69422. array.push = function () {
  69423. var items = [];
  69424. for (var _i = 0; _i < arguments.length; _i++) {
  69425. items[_i] = arguments[_i];
  69426. }
  69427. var result = oldPush.apply(array, items);
  69428. _this._markAllSubMeshesAsTexturesDirty();
  69429. return result;
  69430. };
  69431. var oldSplice = array.splice;
  69432. array.splice = function (index, deleteCount) {
  69433. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69434. _this._markAllSubMeshesAsTexturesDirty();
  69435. return deleted;
  69436. };
  69437. };
  69438. // Properties
  69439. MultiMaterial.prototype.getSubMaterial = function (index) {
  69440. if (index < 0 || index >= this.subMaterials.length) {
  69441. return this.getScene().defaultMaterial;
  69442. }
  69443. return this.subMaterials[index];
  69444. };
  69445. MultiMaterial.prototype.getActiveTextures = function () {
  69446. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69447. if (subMaterial) {
  69448. return subMaterial.getActiveTextures();
  69449. }
  69450. else {
  69451. return [];
  69452. }
  69453. }));
  69454. var _a;
  69455. };
  69456. // Methods
  69457. MultiMaterial.prototype.getClassName = function () {
  69458. return "MultiMaterial";
  69459. };
  69460. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69461. for (var index = 0; index < this.subMaterials.length; index++) {
  69462. var subMaterial = this.subMaterials[index];
  69463. if (subMaterial) {
  69464. if (subMaterial.storeEffectOnSubMeshes) {
  69465. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69466. return false;
  69467. }
  69468. continue;
  69469. }
  69470. if (!subMaterial.isReady(mesh)) {
  69471. return false;
  69472. }
  69473. }
  69474. }
  69475. return true;
  69476. };
  69477. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69478. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69479. for (var index = 0; index < this.subMaterials.length; index++) {
  69480. var subMaterial = null;
  69481. var current = this.subMaterials[index];
  69482. if (cloneChildren && current) {
  69483. subMaterial = current.clone(name + "-" + current.name);
  69484. }
  69485. else {
  69486. subMaterial = this.subMaterials[index];
  69487. }
  69488. newMultiMaterial.subMaterials.push(subMaterial);
  69489. }
  69490. return newMultiMaterial;
  69491. };
  69492. MultiMaterial.prototype.serialize = function () {
  69493. var serializationObject = {};
  69494. serializationObject.name = this.name;
  69495. serializationObject.id = this.id;
  69496. if (BABYLON.Tags) {
  69497. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69498. }
  69499. serializationObject.materials = [];
  69500. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69501. var subMat = this.subMaterials[matIndex];
  69502. if (subMat) {
  69503. serializationObject.materials.push(subMat.id);
  69504. }
  69505. else {
  69506. serializationObject.materials.push(null);
  69507. }
  69508. }
  69509. return serializationObject;
  69510. };
  69511. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69512. var scene = this.getScene();
  69513. if (!scene) {
  69514. return;
  69515. }
  69516. var index = scene.multiMaterials.indexOf(this);
  69517. if (index >= 0) {
  69518. scene.multiMaterials.splice(index, 1);
  69519. }
  69520. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69521. };
  69522. return MultiMaterial;
  69523. }(BABYLON.Material));
  69524. BABYLON.MultiMaterial = MultiMaterial;
  69525. })(BABYLON || (BABYLON = {}));
  69526. //# sourceMappingURL=babylon.multiMaterial.js.map
  69527. var BABYLON;
  69528. (function (BABYLON) {
  69529. var FreeCameraTouchInput = /** @class */ (function () {
  69530. function FreeCameraTouchInput() {
  69531. this._offsetX = null;
  69532. this._offsetY = null;
  69533. this._pointerPressed = new Array();
  69534. this.touchAngularSensibility = 200000.0;
  69535. this.touchMoveSensibility = 250.0;
  69536. }
  69537. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69538. var _this = this;
  69539. var previousPosition = null;
  69540. if (this._pointerInput === undefined) {
  69541. this._onLostFocus = function (evt) {
  69542. _this._offsetX = null;
  69543. _this._offsetY = null;
  69544. };
  69545. this._pointerInput = function (p, s) {
  69546. var evt = p.event;
  69547. if (evt.pointerType === "mouse") {
  69548. return;
  69549. }
  69550. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69551. if (!noPreventDefault) {
  69552. evt.preventDefault();
  69553. }
  69554. _this._pointerPressed.push(evt.pointerId);
  69555. if (_this._pointerPressed.length !== 1) {
  69556. return;
  69557. }
  69558. previousPosition = {
  69559. x: evt.clientX,
  69560. y: evt.clientY
  69561. };
  69562. }
  69563. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69564. if (!noPreventDefault) {
  69565. evt.preventDefault();
  69566. }
  69567. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69568. if (index === -1) {
  69569. return;
  69570. }
  69571. _this._pointerPressed.splice(index, 1);
  69572. if (index != 0) {
  69573. return;
  69574. }
  69575. previousPosition = null;
  69576. _this._offsetX = null;
  69577. _this._offsetY = null;
  69578. }
  69579. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69580. if (!noPreventDefault) {
  69581. evt.preventDefault();
  69582. }
  69583. if (!previousPosition) {
  69584. return;
  69585. }
  69586. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69587. if (index != 0) {
  69588. return;
  69589. }
  69590. _this._offsetX = evt.clientX - previousPosition.x;
  69591. _this._offsetY = -(evt.clientY - previousPosition.y);
  69592. }
  69593. };
  69594. }
  69595. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69596. if (this._onLostFocus) {
  69597. element.addEventListener("blur", this._onLostFocus);
  69598. }
  69599. };
  69600. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69601. if (this._pointerInput && element) {
  69602. if (this._observer) {
  69603. this.camera.getScene().onPointerObservable.remove(this._observer);
  69604. this._observer = null;
  69605. }
  69606. if (this._onLostFocus) {
  69607. element.removeEventListener("blur", this._onLostFocus);
  69608. this._onLostFocus = null;
  69609. }
  69610. this._pointerPressed = [];
  69611. this._offsetX = null;
  69612. this._offsetY = null;
  69613. }
  69614. };
  69615. FreeCameraTouchInput.prototype.checkInputs = function () {
  69616. if (this._offsetX && this._offsetY) {
  69617. var camera = this.camera;
  69618. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69619. if (this._pointerPressed.length > 1) {
  69620. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69621. }
  69622. else {
  69623. var speed = camera._computeLocalCameraSpeed();
  69624. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69625. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69626. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69627. }
  69628. }
  69629. };
  69630. FreeCameraTouchInput.prototype.getClassName = function () {
  69631. return "FreeCameraTouchInput";
  69632. };
  69633. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69634. return "touch";
  69635. };
  69636. __decorate([
  69637. BABYLON.serialize()
  69638. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69639. __decorate([
  69640. BABYLON.serialize()
  69641. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69642. return FreeCameraTouchInput;
  69643. }());
  69644. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69645. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69646. })(BABYLON || (BABYLON = {}));
  69647. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69648. var BABYLON;
  69649. (function (BABYLON) {
  69650. // We're mainly based on the logic defined into the FreeCamera code
  69651. var TouchCamera = /** @class */ (function (_super) {
  69652. __extends(TouchCamera, _super);
  69653. //-- end properties for backward compatibility for inputs
  69654. function TouchCamera(name, position, scene) {
  69655. var _this = _super.call(this, name, position, scene) || this;
  69656. _this.inputs.addTouch();
  69657. _this._setupInputs();
  69658. return _this;
  69659. }
  69660. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69661. //-- Begin properties for backward compatibility for inputs
  69662. get: function () {
  69663. var touch = this.inputs.attached["touch"];
  69664. if (touch)
  69665. return touch.touchAngularSensibility;
  69666. return 0;
  69667. },
  69668. set: function (value) {
  69669. var touch = this.inputs.attached["touch"];
  69670. if (touch)
  69671. touch.touchAngularSensibility = value;
  69672. },
  69673. enumerable: true,
  69674. configurable: true
  69675. });
  69676. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69677. get: function () {
  69678. var touch = this.inputs.attached["touch"];
  69679. if (touch)
  69680. return touch.touchMoveSensibility;
  69681. return 0;
  69682. },
  69683. set: function (value) {
  69684. var touch = this.inputs.attached["touch"];
  69685. if (touch)
  69686. touch.touchMoveSensibility = value;
  69687. },
  69688. enumerable: true,
  69689. configurable: true
  69690. });
  69691. TouchCamera.prototype.getClassName = function () {
  69692. return "TouchCamera";
  69693. };
  69694. TouchCamera.prototype._setupInputs = function () {
  69695. var mouse = this.inputs.attached["mouse"];
  69696. if (mouse) {
  69697. mouse.touchEnabled = false;
  69698. }
  69699. };
  69700. return TouchCamera;
  69701. }(BABYLON.FreeCamera));
  69702. BABYLON.TouchCamera = TouchCamera;
  69703. })(BABYLON || (BABYLON = {}));
  69704. //# sourceMappingURL=babylon.touchCamera.js.map
  69705. var BABYLON;
  69706. (function (BABYLON) {
  69707. var ProceduralTexture = /** @class */ (function (_super) {
  69708. __extends(ProceduralTexture, _super);
  69709. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69710. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69711. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69712. if (isCube === void 0) { isCube = false; }
  69713. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69714. _this.isCube = isCube;
  69715. _this.isEnabled = true;
  69716. _this._currentRefreshId = -1;
  69717. _this._refreshRate = 1;
  69718. _this._vertexBuffers = {};
  69719. _this._uniforms = new Array();
  69720. _this._samplers = new Array();
  69721. _this._textures = {};
  69722. _this._floats = {};
  69723. _this._floatsArrays = {};
  69724. _this._colors3 = {};
  69725. _this._colors4 = {};
  69726. _this._vectors2 = {};
  69727. _this._vectors3 = {};
  69728. _this._matrices = {};
  69729. _this._fallbackTextureUsed = false;
  69730. scene.proceduralTextures.push(_this);
  69731. _this._engine = scene.getEngine();
  69732. _this.name = name;
  69733. _this.isRenderTarget = true;
  69734. _this._size = size;
  69735. _this._generateMipMaps = generateMipMaps;
  69736. _this.setFragment(fragment);
  69737. _this._fallbackTexture = fallbackTexture;
  69738. if (isCube) {
  69739. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69740. _this.setFloat("face", 0);
  69741. }
  69742. else {
  69743. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69744. }
  69745. // VBO
  69746. var vertices = [];
  69747. vertices.push(1, 1);
  69748. vertices.push(-1, 1);
  69749. vertices.push(-1, -1);
  69750. vertices.push(1, -1);
  69751. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69752. _this._createIndexBuffer();
  69753. return _this;
  69754. }
  69755. ProceduralTexture.prototype._createIndexBuffer = function () {
  69756. var engine = this._engine;
  69757. // Indices
  69758. var indices = [];
  69759. indices.push(0);
  69760. indices.push(1);
  69761. indices.push(2);
  69762. indices.push(0);
  69763. indices.push(2);
  69764. indices.push(3);
  69765. this._indexBuffer = engine.createIndexBuffer(indices);
  69766. };
  69767. ProceduralTexture.prototype._rebuild = function () {
  69768. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69769. if (vb) {
  69770. vb._rebuild();
  69771. }
  69772. this._createIndexBuffer();
  69773. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69774. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69775. }
  69776. };
  69777. ProceduralTexture.prototype.reset = function () {
  69778. if (this._effect === undefined) {
  69779. return;
  69780. }
  69781. var engine = this._engine;
  69782. engine._releaseEffect(this._effect);
  69783. };
  69784. ProceduralTexture.prototype.isReady = function () {
  69785. var _this = this;
  69786. var engine = this._engine;
  69787. var shaders;
  69788. if (!this._fragment) {
  69789. return false;
  69790. }
  69791. if (this._fallbackTextureUsed) {
  69792. return true;
  69793. }
  69794. if (this._fragment.fragmentElement !== undefined) {
  69795. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69796. }
  69797. else {
  69798. shaders = { vertex: "procedural", fragment: this._fragment };
  69799. }
  69800. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69801. _this.releaseInternalTexture();
  69802. if (_this._fallbackTexture) {
  69803. _this._texture = _this._fallbackTexture._texture;
  69804. if (_this._texture) {
  69805. _this._texture.incrementReferences();
  69806. }
  69807. }
  69808. _this._fallbackTextureUsed = true;
  69809. });
  69810. return this._effect.isReady();
  69811. };
  69812. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69813. this._currentRefreshId = -1;
  69814. };
  69815. ProceduralTexture.prototype.setFragment = function (fragment) {
  69816. this._fragment = fragment;
  69817. };
  69818. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69819. get: function () {
  69820. return this._refreshRate;
  69821. },
  69822. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69823. set: function (value) {
  69824. this._refreshRate = value;
  69825. this.resetRefreshCounter();
  69826. },
  69827. enumerable: true,
  69828. configurable: true
  69829. });
  69830. ProceduralTexture.prototype._shouldRender = function () {
  69831. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69832. return false;
  69833. }
  69834. if (this._fallbackTextureUsed) {
  69835. return false;
  69836. }
  69837. if (this._currentRefreshId === -1) { // At least render once
  69838. this._currentRefreshId = 1;
  69839. return true;
  69840. }
  69841. if (this.refreshRate === this._currentRefreshId) {
  69842. this._currentRefreshId = 1;
  69843. return true;
  69844. }
  69845. this._currentRefreshId++;
  69846. return false;
  69847. };
  69848. ProceduralTexture.prototype.getRenderSize = function () {
  69849. return this._size;
  69850. };
  69851. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69852. if (this._fallbackTextureUsed) {
  69853. return;
  69854. }
  69855. this.releaseInternalTexture();
  69856. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69857. };
  69858. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69859. if (this._uniforms.indexOf(uniformName) === -1) {
  69860. this._uniforms.push(uniformName);
  69861. }
  69862. };
  69863. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69864. if (this._samplers.indexOf(name) === -1) {
  69865. this._samplers.push(name);
  69866. }
  69867. this._textures[name] = texture;
  69868. return this;
  69869. };
  69870. ProceduralTexture.prototype.setFloat = function (name, value) {
  69871. this._checkUniform(name);
  69872. this._floats[name] = value;
  69873. return this;
  69874. };
  69875. ProceduralTexture.prototype.setFloats = function (name, value) {
  69876. this._checkUniform(name);
  69877. this._floatsArrays[name] = value;
  69878. return this;
  69879. };
  69880. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69881. this._checkUniform(name);
  69882. this._colors3[name] = value;
  69883. return this;
  69884. };
  69885. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69886. this._checkUniform(name);
  69887. this._colors4[name] = value;
  69888. return this;
  69889. };
  69890. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69891. this._checkUniform(name);
  69892. this._vectors2[name] = value;
  69893. return this;
  69894. };
  69895. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69896. this._checkUniform(name);
  69897. this._vectors3[name] = value;
  69898. return this;
  69899. };
  69900. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69901. this._checkUniform(name);
  69902. this._matrices[name] = value;
  69903. return this;
  69904. };
  69905. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69906. var scene = this.getScene();
  69907. if (!scene) {
  69908. return;
  69909. }
  69910. var engine = this._engine;
  69911. // Render
  69912. engine.enableEffect(this._effect);
  69913. engine.setState(false);
  69914. // Texture
  69915. for (var name in this._textures) {
  69916. this._effect.setTexture(name, this._textures[name]);
  69917. }
  69918. // Float
  69919. for (name in this._floats) {
  69920. this._effect.setFloat(name, this._floats[name]);
  69921. }
  69922. // Floats
  69923. for (name in this._floatsArrays) {
  69924. this._effect.setArray(name, this._floatsArrays[name]);
  69925. }
  69926. // Color3
  69927. for (name in this._colors3) {
  69928. this._effect.setColor3(name, this._colors3[name]);
  69929. }
  69930. // Color4
  69931. for (name in this._colors4) {
  69932. var color = this._colors4[name];
  69933. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69934. }
  69935. // Vector2
  69936. for (name in this._vectors2) {
  69937. this._effect.setVector2(name, this._vectors2[name]);
  69938. }
  69939. // Vector3
  69940. for (name in this._vectors3) {
  69941. this._effect.setVector3(name, this._vectors3[name]);
  69942. }
  69943. // Matrix
  69944. for (name in this._matrices) {
  69945. this._effect.setMatrix(name, this._matrices[name]);
  69946. }
  69947. if (!this._texture) {
  69948. return;
  69949. }
  69950. if (this.isCube) {
  69951. for (var face = 0; face < 6; face++) {
  69952. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69953. // VBOs
  69954. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69955. this._effect.setFloat("face", face);
  69956. // Clear
  69957. engine.clear(scene.clearColor, true, true, true);
  69958. // Draw order
  69959. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69960. // Mipmaps
  69961. if (face === 5) {
  69962. engine.generateMipMapsForCubemap(this._texture);
  69963. }
  69964. }
  69965. }
  69966. else {
  69967. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69968. // VBOs
  69969. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69970. // Clear
  69971. engine.clear(scene.clearColor, true, true, true);
  69972. // Draw order
  69973. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69974. }
  69975. // Unbind
  69976. engine.unBindFramebuffer(this._texture, this.isCube);
  69977. if (this.onGenerated) {
  69978. this.onGenerated();
  69979. }
  69980. };
  69981. ProceduralTexture.prototype.clone = function () {
  69982. var textureSize = this.getSize();
  69983. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69984. // Base texture
  69985. newTexture.hasAlpha = this.hasAlpha;
  69986. newTexture.level = this.level;
  69987. // RenderTarget Texture
  69988. newTexture.coordinatesMode = this.coordinatesMode;
  69989. return newTexture;
  69990. };
  69991. ProceduralTexture.prototype.dispose = function () {
  69992. var scene = this.getScene();
  69993. if (!scene) {
  69994. return;
  69995. }
  69996. var index = scene.proceduralTextures.indexOf(this);
  69997. if (index >= 0) {
  69998. scene.proceduralTextures.splice(index, 1);
  69999. }
  70000. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70001. if (vertexBuffer) {
  70002. vertexBuffer.dispose();
  70003. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70004. }
  70005. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70006. this._indexBuffer = null;
  70007. }
  70008. _super.prototype.dispose.call(this);
  70009. };
  70010. return ProceduralTexture;
  70011. }(BABYLON.Texture));
  70012. BABYLON.ProceduralTexture = ProceduralTexture;
  70013. })(BABYLON || (BABYLON = {}));
  70014. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70015. var BABYLON;
  70016. (function (BABYLON) {
  70017. var CustomProceduralTexture = /** @class */ (function (_super) {
  70018. __extends(CustomProceduralTexture, _super);
  70019. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70020. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70021. _this._animate = true;
  70022. _this._time = 0;
  70023. _this._texturePath = texturePath;
  70024. //Try to load json
  70025. _this.loadJson(texturePath);
  70026. _this.refreshRate = 1;
  70027. return _this;
  70028. }
  70029. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70030. var _this = this;
  70031. var noConfigFile = function () {
  70032. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70033. try {
  70034. _this.setFragment(_this._texturePath);
  70035. }
  70036. catch (ex) {
  70037. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70038. }
  70039. };
  70040. var configFileUrl = jsonUrl + "/config.json";
  70041. var xhr = new XMLHttpRequest();
  70042. xhr.open("GET", configFileUrl, true);
  70043. xhr.addEventListener("load", function () {
  70044. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70045. try {
  70046. _this._config = JSON.parse(xhr.response);
  70047. _this.updateShaderUniforms();
  70048. _this.updateTextures();
  70049. _this.setFragment(_this._texturePath + "/custom");
  70050. _this._animate = _this._config.animate;
  70051. _this.refreshRate = _this._config.refreshrate;
  70052. }
  70053. catch (ex) {
  70054. noConfigFile();
  70055. }
  70056. }
  70057. else {
  70058. noConfigFile();
  70059. }
  70060. }, false);
  70061. xhr.addEventListener("error", function () {
  70062. noConfigFile();
  70063. }, false);
  70064. try {
  70065. xhr.send();
  70066. }
  70067. catch (ex) {
  70068. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70069. }
  70070. };
  70071. CustomProceduralTexture.prototype.isReady = function () {
  70072. if (!_super.prototype.isReady.call(this)) {
  70073. return false;
  70074. }
  70075. for (var name in this._textures) {
  70076. var texture = this._textures[name];
  70077. if (!texture.isReady()) {
  70078. return false;
  70079. }
  70080. }
  70081. return true;
  70082. };
  70083. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70084. var scene = this.getScene();
  70085. if (this._animate && scene) {
  70086. this._time += scene.getAnimationRatio() * 0.03;
  70087. this.updateShaderUniforms();
  70088. }
  70089. _super.prototype.render.call(this, useCameraPostProcess);
  70090. };
  70091. CustomProceduralTexture.prototype.updateTextures = function () {
  70092. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70093. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70094. }
  70095. };
  70096. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70097. if (this._config) {
  70098. for (var j = 0; j < this._config.uniforms.length; j++) {
  70099. var uniform = this._config.uniforms[j];
  70100. switch (uniform.type) {
  70101. case "float":
  70102. this.setFloat(uniform.name, uniform.value);
  70103. break;
  70104. case "color3":
  70105. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70106. break;
  70107. case "color4":
  70108. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70109. break;
  70110. case "vector2":
  70111. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70112. break;
  70113. case "vector3":
  70114. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70115. break;
  70116. }
  70117. }
  70118. }
  70119. this.setFloat("time", this._time);
  70120. };
  70121. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70122. get: function () {
  70123. return this._animate;
  70124. },
  70125. set: function (value) {
  70126. this._animate = value;
  70127. },
  70128. enumerable: true,
  70129. configurable: true
  70130. });
  70131. return CustomProceduralTexture;
  70132. }(BABYLON.ProceduralTexture));
  70133. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70134. })(BABYLON || (BABYLON = {}));
  70135. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70136. var BABYLON;
  70137. (function (BABYLON) {
  70138. var FreeCameraGamepadInput = /** @class */ (function () {
  70139. function FreeCameraGamepadInput() {
  70140. this.gamepadAngularSensibility = 200;
  70141. this.gamepadMoveSensibility = 40;
  70142. // private members
  70143. this._cameraTransform = BABYLON.Matrix.Identity();
  70144. this._deltaTransform = BABYLON.Vector3.Zero();
  70145. this._vector3 = BABYLON.Vector3.Zero();
  70146. this._vector2 = BABYLON.Vector2.Zero();
  70147. }
  70148. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70149. var _this = this;
  70150. var manager = this.camera.getScene().gamepadManager;
  70151. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70152. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70153. // prioritize XBOX gamepads.
  70154. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70155. _this.gamepad = gamepad;
  70156. }
  70157. }
  70158. });
  70159. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70160. if (_this.gamepad === gamepad) {
  70161. _this.gamepad = null;
  70162. }
  70163. });
  70164. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70165. };
  70166. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70167. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70168. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70169. this.gamepad = null;
  70170. };
  70171. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70172. if (this.gamepad && this.gamepad.leftStick) {
  70173. var camera = this.camera;
  70174. var LSValues = this.gamepad.leftStick;
  70175. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70176. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70177. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70178. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70179. var RSValues = this.gamepad.rightStick;
  70180. if (RSValues) {
  70181. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70182. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70183. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70184. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70185. }
  70186. else {
  70187. RSValues = { x: 0, y: 0 };
  70188. }
  70189. if (!camera.rotationQuaternion) {
  70190. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70191. }
  70192. else {
  70193. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70194. }
  70195. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70196. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70197. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70198. camera.cameraDirection.addInPlace(this._deltaTransform);
  70199. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70200. camera.cameraRotation.addInPlace(this._vector2);
  70201. }
  70202. };
  70203. FreeCameraGamepadInput.prototype.getClassName = function () {
  70204. return "FreeCameraGamepadInput";
  70205. };
  70206. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70207. return "gamepad";
  70208. };
  70209. __decorate([
  70210. BABYLON.serialize()
  70211. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70212. __decorate([
  70213. BABYLON.serialize()
  70214. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70215. return FreeCameraGamepadInput;
  70216. }());
  70217. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70218. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70219. })(BABYLON || (BABYLON = {}));
  70220. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70221. var BABYLON;
  70222. (function (BABYLON) {
  70223. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70224. function ArcRotateCameraGamepadInput() {
  70225. this.gamepadRotationSensibility = 80;
  70226. this.gamepadMoveSensibility = 40;
  70227. }
  70228. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70229. var _this = this;
  70230. var manager = this.camera.getScene().gamepadManager;
  70231. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70232. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70233. // prioritize XBOX gamepads.
  70234. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70235. _this.gamepad = gamepad;
  70236. }
  70237. }
  70238. });
  70239. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70240. if (_this.gamepad === gamepad) {
  70241. _this.gamepad = null;
  70242. }
  70243. });
  70244. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70245. };
  70246. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70247. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70248. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70249. this.gamepad = null;
  70250. };
  70251. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70252. if (this.gamepad) {
  70253. var camera = this.camera;
  70254. var RSValues = this.gamepad.rightStick;
  70255. if (RSValues) {
  70256. if (RSValues.x != 0) {
  70257. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70258. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70259. camera.inertialAlphaOffset += normalizedRX;
  70260. }
  70261. }
  70262. if (RSValues.y != 0) {
  70263. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70264. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70265. camera.inertialBetaOffset += normalizedRY;
  70266. }
  70267. }
  70268. }
  70269. var LSValues = this.gamepad.leftStick;
  70270. if (LSValues && LSValues.y != 0) {
  70271. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70272. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70273. this.camera.inertialRadiusOffset -= normalizedLY;
  70274. }
  70275. }
  70276. }
  70277. };
  70278. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70279. return "ArcRotateCameraGamepadInput";
  70280. };
  70281. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70282. return "gamepad";
  70283. };
  70284. __decorate([
  70285. BABYLON.serialize()
  70286. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70287. __decorate([
  70288. BABYLON.serialize()
  70289. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70290. return ArcRotateCameraGamepadInput;
  70291. }());
  70292. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70293. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70294. })(BABYLON || (BABYLON = {}));
  70295. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70296. var BABYLON;
  70297. (function (BABYLON) {
  70298. var GamepadManager = /** @class */ (function () {
  70299. function GamepadManager(_scene) {
  70300. var _this = this;
  70301. this._scene = _scene;
  70302. this._babylonGamepads = [];
  70303. this._oneGamepadConnected = false;
  70304. this._isMonitoring = false;
  70305. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70306. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70307. this._gamepadEventSupported = false;
  70308. }
  70309. else {
  70310. this._gamepadEventSupported = 'GamepadEvent' in window;
  70311. this._gamepadSupport = (navigator.getGamepads ||
  70312. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70313. }
  70314. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70315. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70316. for (var i in _this._babylonGamepads) {
  70317. var gamepad = _this._babylonGamepads[i];
  70318. if (gamepad && gamepad._isConnected) {
  70319. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70320. }
  70321. }
  70322. });
  70323. this._onGamepadConnectedEvent = function (evt) {
  70324. var gamepad = evt.gamepad;
  70325. if (gamepad.index in _this._babylonGamepads) {
  70326. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70327. return;
  70328. }
  70329. }
  70330. var newGamepad;
  70331. if (_this._babylonGamepads[gamepad.index]) {
  70332. newGamepad = _this._babylonGamepads[gamepad.index];
  70333. newGamepad.browserGamepad = gamepad;
  70334. newGamepad._isConnected = true;
  70335. }
  70336. else {
  70337. newGamepad = _this._addNewGamepad(gamepad);
  70338. }
  70339. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70340. _this._startMonitoringGamepads();
  70341. };
  70342. this._onGamepadDisconnectedEvent = function (evt) {
  70343. var gamepad = evt.gamepad;
  70344. // Remove the gamepad from the list of gamepads to monitor.
  70345. for (var i in _this._babylonGamepads) {
  70346. if (_this._babylonGamepads[i].index === gamepad.index) {
  70347. var disconnectedGamepad = _this._babylonGamepads[i];
  70348. disconnectedGamepad._isConnected = false;
  70349. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70350. break;
  70351. }
  70352. }
  70353. };
  70354. if (this._gamepadSupport) {
  70355. //first add already-connected gamepads
  70356. this._updateGamepadObjects();
  70357. if (this._babylonGamepads.length) {
  70358. this._startMonitoringGamepads();
  70359. }
  70360. // Checking if the gamepad connected event is supported (like in Firefox)
  70361. if (this._gamepadEventSupported) {
  70362. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70363. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70364. }
  70365. else {
  70366. this._startMonitoringGamepads();
  70367. }
  70368. }
  70369. }
  70370. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70371. get: function () {
  70372. return this._babylonGamepads;
  70373. },
  70374. enumerable: true,
  70375. configurable: true
  70376. });
  70377. GamepadManager.prototype.getGamepadByType = function (type) {
  70378. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70379. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70380. var gamepad = _a[_i];
  70381. if (gamepad && gamepad.type === type) {
  70382. return gamepad;
  70383. }
  70384. }
  70385. return null;
  70386. };
  70387. GamepadManager.prototype.dispose = function () {
  70388. if (this._gamepadEventSupported) {
  70389. if (this._onGamepadConnectedEvent) {
  70390. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70391. }
  70392. if (this._onGamepadDisconnectedEvent) {
  70393. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70394. }
  70395. this._onGamepadConnectedEvent = null;
  70396. this._onGamepadDisconnectedEvent = null;
  70397. }
  70398. this._babylonGamepads.forEach(function (gamepad) {
  70399. gamepad.dispose();
  70400. });
  70401. this.onGamepadConnectedObservable.clear();
  70402. this.onGamepadDisconnectedObservable.clear();
  70403. this._oneGamepadConnected = false;
  70404. this._stopMonitoringGamepads();
  70405. this._babylonGamepads = [];
  70406. };
  70407. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70408. if (!this._oneGamepadConnected) {
  70409. this._oneGamepadConnected = true;
  70410. }
  70411. var newGamepad;
  70412. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70413. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70414. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70415. }
  70416. // if pose is supported, use the (WebVR) pose enabled controller
  70417. else if (gamepad.pose) {
  70418. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70419. }
  70420. else {
  70421. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70422. }
  70423. this._babylonGamepads[newGamepad.index] = newGamepad;
  70424. return newGamepad;
  70425. };
  70426. GamepadManager.prototype._startMonitoringGamepads = function () {
  70427. if (!this._isMonitoring) {
  70428. this._isMonitoring = true;
  70429. //back-comp
  70430. if (!this._scene) {
  70431. this._checkGamepadsStatus();
  70432. }
  70433. }
  70434. };
  70435. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70436. this._isMonitoring = false;
  70437. };
  70438. GamepadManager.prototype._checkGamepadsStatus = function () {
  70439. var _this = this;
  70440. // Hack to be compatible Chrome
  70441. this._updateGamepadObjects();
  70442. for (var i in this._babylonGamepads) {
  70443. var gamepad = this._babylonGamepads[i];
  70444. if (!gamepad || !gamepad.isConnected) {
  70445. continue;
  70446. }
  70447. gamepad.update();
  70448. }
  70449. if (this._isMonitoring && !this._scene) {
  70450. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70451. }
  70452. };
  70453. // This function is called only on Chrome, which does not properly support
  70454. // connection/disconnection events and forces you to recopy again the gamepad object
  70455. GamepadManager.prototype._updateGamepadObjects = function () {
  70456. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70457. for (var i = 0; i < gamepads.length; i++) {
  70458. var gamepad = gamepads[i];
  70459. if (gamepad) {
  70460. if (!this._babylonGamepads[gamepad.index]) {
  70461. var newGamepad = this._addNewGamepad(gamepad);
  70462. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70463. }
  70464. else {
  70465. // Forced to copy again this object for Chrome for unknown reason
  70466. this._babylonGamepads[i].browserGamepad = gamepad;
  70467. if (!this._babylonGamepads[i].isConnected) {
  70468. this._babylonGamepads[i]._isConnected = true;
  70469. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70470. }
  70471. }
  70472. }
  70473. }
  70474. };
  70475. return GamepadManager;
  70476. }());
  70477. BABYLON.GamepadManager = GamepadManager;
  70478. })(BABYLON || (BABYLON = {}));
  70479. //# sourceMappingURL=babylon.gamepadManager.js.map
  70480. var BABYLON;
  70481. (function (BABYLON) {
  70482. var StickValues = /** @class */ (function () {
  70483. function StickValues(x, y) {
  70484. this.x = x;
  70485. this.y = y;
  70486. }
  70487. return StickValues;
  70488. }());
  70489. BABYLON.StickValues = StickValues;
  70490. var Gamepad = /** @class */ (function () {
  70491. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70492. if (leftStickX === void 0) { leftStickX = 0; }
  70493. if (leftStickY === void 0) { leftStickY = 1; }
  70494. if (rightStickX === void 0) { rightStickX = 2; }
  70495. if (rightStickY === void 0) { rightStickY = 3; }
  70496. this.id = id;
  70497. this.index = index;
  70498. this.browserGamepad = browserGamepad;
  70499. this._isConnected = true;
  70500. this._invertLeftStickY = false;
  70501. this.type = Gamepad.GAMEPAD;
  70502. this._leftStickAxisX = leftStickX;
  70503. this._leftStickAxisY = leftStickY;
  70504. this._rightStickAxisX = rightStickX;
  70505. this._rightStickAxisY = rightStickY;
  70506. if (this.browserGamepad.axes.length >= 2) {
  70507. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70508. }
  70509. if (this.browserGamepad.axes.length >= 4) {
  70510. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70511. }
  70512. }
  70513. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70514. get: function () {
  70515. return this._isConnected;
  70516. },
  70517. enumerable: true,
  70518. configurable: true
  70519. });
  70520. Gamepad.prototype.onleftstickchanged = function (callback) {
  70521. this._onleftstickchanged = callback;
  70522. };
  70523. Gamepad.prototype.onrightstickchanged = function (callback) {
  70524. this._onrightstickchanged = callback;
  70525. };
  70526. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70527. get: function () {
  70528. return this._leftStick;
  70529. },
  70530. set: function (newValues) {
  70531. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70532. this._onleftstickchanged(newValues);
  70533. }
  70534. this._leftStick = newValues;
  70535. },
  70536. enumerable: true,
  70537. configurable: true
  70538. });
  70539. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70540. get: function () {
  70541. return this._rightStick;
  70542. },
  70543. set: function (newValues) {
  70544. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70545. this._onrightstickchanged(newValues);
  70546. }
  70547. this._rightStick = newValues;
  70548. },
  70549. enumerable: true,
  70550. configurable: true
  70551. });
  70552. Gamepad.prototype.update = function () {
  70553. if (this._leftStick) {
  70554. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70555. if (this._invertLeftStickY) {
  70556. this.leftStick.y *= -1;
  70557. }
  70558. }
  70559. if (this._rightStick) {
  70560. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70561. }
  70562. };
  70563. Gamepad.prototype.dispose = function () {
  70564. };
  70565. Gamepad.GAMEPAD = 0;
  70566. Gamepad.GENERIC = 1;
  70567. Gamepad.XBOX = 2;
  70568. Gamepad.POSE_ENABLED = 3;
  70569. return Gamepad;
  70570. }());
  70571. BABYLON.Gamepad = Gamepad;
  70572. var GenericPad = /** @class */ (function (_super) {
  70573. __extends(GenericPad, _super);
  70574. function GenericPad(id, index, browserGamepad) {
  70575. var _this = _super.call(this, id, index, browserGamepad) || this;
  70576. _this.onButtonDownObservable = new BABYLON.Observable();
  70577. _this.onButtonUpObservable = new BABYLON.Observable();
  70578. _this.type = Gamepad.GENERIC;
  70579. _this._buttons = new Array(browserGamepad.buttons.length);
  70580. return _this;
  70581. }
  70582. GenericPad.prototype.onbuttondown = function (callback) {
  70583. this._onbuttondown = callback;
  70584. };
  70585. GenericPad.prototype.onbuttonup = function (callback) {
  70586. this._onbuttonup = callback;
  70587. };
  70588. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70589. if (newValue !== currentValue) {
  70590. if (newValue === 1) {
  70591. if (this._onbuttondown) {
  70592. this._onbuttondown(buttonIndex);
  70593. }
  70594. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70595. }
  70596. if (newValue === 0) {
  70597. if (this._onbuttonup) {
  70598. this._onbuttonup(buttonIndex);
  70599. }
  70600. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70601. }
  70602. }
  70603. return newValue;
  70604. };
  70605. GenericPad.prototype.update = function () {
  70606. _super.prototype.update.call(this);
  70607. for (var index = 0; index < this._buttons.length; index++) {
  70608. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70609. }
  70610. };
  70611. GenericPad.prototype.dispose = function () {
  70612. _super.prototype.dispose.call(this);
  70613. this.onButtonDownObservable.clear();
  70614. this.onButtonUpObservable.clear();
  70615. };
  70616. return GenericPad;
  70617. }(Gamepad));
  70618. BABYLON.GenericPad = GenericPad;
  70619. })(BABYLON || (BABYLON = {}));
  70620. //# sourceMappingURL=babylon.gamepad.js.map
  70621. var BABYLON;
  70622. (function (BABYLON) {
  70623. /**
  70624. * Defines supported buttons for XBox360 compatible gamepads
  70625. */
  70626. var Xbox360Button;
  70627. (function (Xbox360Button) {
  70628. /** A */
  70629. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70630. /** B */
  70631. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70632. /** X */
  70633. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70634. /** Y */
  70635. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70636. /** Start */
  70637. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70638. /** Back */
  70639. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70640. /** Left button */
  70641. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70642. /** Right button */
  70643. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70644. /** Left stick */
  70645. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70646. /** Right stick */
  70647. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70648. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70649. /** Defines values for XBox360 DPad */
  70650. var Xbox360Dpad;
  70651. (function (Xbox360Dpad) {
  70652. /** Up */
  70653. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70654. /** Down */
  70655. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70656. /** Left */
  70657. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70658. /** Right */
  70659. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70660. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70661. /**
  70662. * Defines a XBox360 gamepad
  70663. */
  70664. var Xbox360Pad = /** @class */ (function (_super) {
  70665. __extends(Xbox360Pad, _super);
  70666. /**
  70667. * Creates a new XBox360 gamepad object
  70668. * @param id defines the id of this gamepad
  70669. * @param index defines its index
  70670. * @param gamepad defines the internal HTML gamepad object
  70671. * @param xboxOne defines if it is a XBox One gamepad
  70672. */
  70673. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70674. if (xboxOne === void 0) { xboxOne = false; }
  70675. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70676. _this._leftTrigger = 0;
  70677. _this._rightTrigger = 0;
  70678. /** Observable raised when a button is pressed */
  70679. _this.onButtonDownObservable = new BABYLON.Observable();
  70680. /** Observable raised when a button is released */
  70681. _this.onButtonUpObservable = new BABYLON.Observable();
  70682. /** Observable raised when a pad is pressed */
  70683. _this.onPadDownObservable = new BABYLON.Observable();
  70684. /** Observable raised when a pad is released */
  70685. _this.onPadUpObservable = new BABYLON.Observable();
  70686. _this._buttonA = 0;
  70687. _this._buttonB = 0;
  70688. _this._buttonX = 0;
  70689. _this._buttonY = 0;
  70690. _this._buttonBack = 0;
  70691. _this._buttonStart = 0;
  70692. _this._buttonLB = 0;
  70693. _this._buttonRB = 0;
  70694. _this._buttonLeftStick = 0;
  70695. _this._buttonRightStick = 0;
  70696. _this._dPadUp = 0;
  70697. _this._dPadDown = 0;
  70698. _this._dPadLeft = 0;
  70699. _this._dPadRight = 0;
  70700. _this._isXboxOnePad = false;
  70701. _this.type = BABYLON.Gamepad.XBOX;
  70702. _this._isXboxOnePad = xboxOne;
  70703. return _this;
  70704. }
  70705. /**
  70706. * Defines the callback to call when left trigger is pressed
  70707. * @param callback defines the callback to use
  70708. */
  70709. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70710. this._onlefttriggerchanged = callback;
  70711. };
  70712. /**
  70713. * Defines the callback to call when right trigger is pressed
  70714. * @param callback defines the callback to use
  70715. */
  70716. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70717. this._onrighttriggerchanged = callback;
  70718. };
  70719. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70720. /**
  70721. * Gets or sets left trigger value
  70722. */
  70723. get: function () {
  70724. return this._leftTrigger;
  70725. },
  70726. set: function (newValue) {
  70727. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70728. this._onlefttriggerchanged(newValue);
  70729. }
  70730. this._leftTrigger = newValue;
  70731. },
  70732. enumerable: true,
  70733. configurable: true
  70734. });
  70735. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70736. /**
  70737. * Gets or sets right trigger value
  70738. */
  70739. get: function () {
  70740. return this._rightTrigger;
  70741. },
  70742. set: function (newValue) {
  70743. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70744. this._onrighttriggerchanged(newValue);
  70745. }
  70746. this._rightTrigger = newValue;
  70747. },
  70748. enumerable: true,
  70749. configurable: true
  70750. });
  70751. /**
  70752. * Defines the callback to call when a button is pressed
  70753. * @param callback defines the callback to use
  70754. */
  70755. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70756. this._onbuttondown = callback;
  70757. };
  70758. /**
  70759. * Defines the callback to call when a button is released
  70760. * @param callback defines the callback to use
  70761. */
  70762. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70763. this._onbuttonup = callback;
  70764. };
  70765. /**
  70766. * Defines the callback to call when a pad is pressed
  70767. * @param callback defines the callback to use
  70768. */
  70769. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70770. this._ondpaddown = callback;
  70771. };
  70772. /**
  70773. * Defines the callback to call when a pad is released
  70774. * @param callback defines the callback to use
  70775. */
  70776. Xbox360Pad.prototype.ondpadup = function (callback) {
  70777. this._ondpadup = callback;
  70778. };
  70779. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70780. if (newValue !== currentValue) {
  70781. if (newValue === 1) {
  70782. if (this._onbuttondown) {
  70783. this._onbuttondown(buttonType);
  70784. }
  70785. this.onButtonDownObservable.notifyObservers(buttonType);
  70786. }
  70787. if (newValue === 0) {
  70788. if (this._onbuttonup) {
  70789. this._onbuttonup(buttonType);
  70790. }
  70791. this.onButtonUpObservable.notifyObservers(buttonType);
  70792. }
  70793. }
  70794. return newValue;
  70795. };
  70796. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70797. if (newValue !== currentValue) {
  70798. if (newValue === 1) {
  70799. if (this._ondpaddown) {
  70800. this._ondpaddown(buttonType);
  70801. }
  70802. this.onPadDownObservable.notifyObservers(buttonType);
  70803. }
  70804. if (newValue === 0) {
  70805. if (this._ondpadup) {
  70806. this._ondpadup(buttonType);
  70807. }
  70808. this.onPadUpObservable.notifyObservers(buttonType);
  70809. }
  70810. }
  70811. return newValue;
  70812. };
  70813. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70814. /** Gets or sets value of A button */
  70815. get: function () {
  70816. return this._buttonA;
  70817. },
  70818. set: function (value) {
  70819. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70820. },
  70821. enumerable: true,
  70822. configurable: true
  70823. });
  70824. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70825. /** Gets or sets value of B button */
  70826. get: function () {
  70827. return this._buttonB;
  70828. },
  70829. set: function (value) {
  70830. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70831. },
  70832. enumerable: true,
  70833. configurable: true
  70834. });
  70835. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70836. /** Gets or sets value of X button */
  70837. get: function () {
  70838. return this._buttonX;
  70839. },
  70840. set: function (value) {
  70841. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70842. },
  70843. enumerable: true,
  70844. configurable: true
  70845. });
  70846. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70847. /** Gets or sets value of Y button */
  70848. get: function () {
  70849. return this._buttonY;
  70850. },
  70851. set: function (value) {
  70852. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70853. },
  70854. enumerable: true,
  70855. configurable: true
  70856. });
  70857. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70858. /** Gets or sets value of Start button */
  70859. get: function () {
  70860. return this._buttonStart;
  70861. },
  70862. set: function (value) {
  70863. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70864. },
  70865. enumerable: true,
  70866. configurable: true
  70867. });
  70868. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70869. /** Gets or sets value of Back button */
  70870. get: function () {
  70871. return this._buttonBack;
  70872. },
  70873. set: function (value) {
  70874. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70875. },
  70876. enumerable: true,
  70877. configurable: true
  70878. });
  70879. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70880. /** Gets or sets value of Left button */
  70881. get: function () {
  70882. return this._buttonLB;
  70883. },
  70884. set: function (value) {
  70885. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70886. },
  70887. enumerable: true,
  70888. configurable: true
  70889. });
  70890. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70891. /** Gets or sets value of Right button */
  70892. get: function () {
  70893. return this._buttonRB;
  70894. },
  70895. set: function (value) {
  70896. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70897. },
  70898. enumerable: true,
  70899. configurable: true
  70900. });
  70901. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70902. /** Gets or sets value of left stick */
  70903. get: function () {
  70904. return this._buttonLeftStick;
  70905. },
  70906. set: function (value) {
  70907. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70908. },
  70909. enumerable: true,
  70910. configurable: true
  70911. });
  70912. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70913. /** Gets or sets value of right stick */
  70914. get: function () {
  70915. return this._buttonRightStick;
  70916. },
  70917. set: function (value) {
  70918. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70919. },
  70920. enumerable: true,
  70921. configurable: true
  70922. });
  70923. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70924. /** Gets or sets value of DPad up */
  70925. get: function () {
  70926. return this._dPadUp;
  70927. },
  70928. set: function (value) {
  70929. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70930. },
  70931. enumerable: true,
  70932. configurable: true
  70933. });
  70934. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70935. /** Gets or sets value of DPad down */
  70936. get: function () {
  70937. return this._dPadDown;
  70938. },
  70939. set: function (value) {
  70940. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70941. },
  70942. enumerable: true,
  70943. configurable: true
  70944. });
  70945. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70946. /** Gets or sets value of DPad left */
  70947. get: function () {
  70948. return this._dPadLeft;
  70949. },
  70950. set: function (value) {
  70951. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70952. },
  70953. enumerable: true,
  70954. configurable: true
  70955. });
  70956. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70957. /** Gets or sets value of DPad right */
  70958. get: function () {
  70959. return this._dPadRight;
  70960. },
  70961. set: function (value) {
  70962. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70963. },
  70964. enumerable: true,
  70965. configurable: true
  70966. });
  70967. /**
  70968. * Force the gamepad to synchronize with device values
  70969. */
  70970. Xbox360Pad.prototype.update = function () {
  70971. _super.prototype.update.call(this);
  70972. if (this._isXboxOnePad) {
  70973. this.buttonA = this.browserGamepad.buttons[0].value;
  70974. this.buttonB = this.browserGamepad.buttons[1].value;
  70975. this.buttonX = this.browserGamepad.buttons[2].value;
  70976. this.buttonY = this.browserGamepad.buttons[3].value;
  70977. this.buttonLB = this.browserGamepad.buttons[4].value;
  70978. this.buttonRB = this.browserGamepad.buttons[5].value;
  70979. this.leftTrigger = this.browserGamepad.axes[2];
  70980. this.rightTrigger = this.browserGamepad.axes[5];
  70981. this.buttonBack = this.browserGamepad.buttons[9].value;
  70982. this.buttonStart = this.browserGamepad.buttons[8].value;
  70983. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70984. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70985. this.dPadUp = this.browserGamepad.buttons[11].value;
  70986. this.dPadDown = this.browserGamepad.buttons[12].value;
  70987. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70988. this.dPadRight = this.browserGamepad.buttons[14].value;
  70989. }
  70990. else {
  70991. this.buttonA = this.browserGamepad.buttons[0].value;
  70992. this.buttonB = this.browserGamepad.buttons[1].value;
  70993. this.buttonX = this.browserGamepad.buttons[2].value;
  70994. this.buttonY = this.browserGamepad.buttons[3].value;
  70995. this.buttonLB = this.browserGamepad.buttons[4].value;
  70996. this.buttonRB = this.browserGamepad.buttons[5].value;
  70997. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70998. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70999. this.buttonBack = this.browserGamepad.buttons[8].value;
  71000. this.buttonStart = this.browserGamepad.buttons[9].value;
  71001. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71002. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71003. this.dPadUp = this.browserGamepad.buttons[12].value;
  71004. this.dPadDown = this.browserGamepad.buttons[13].value;
  71005. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71006. this.dPadRight = this.browserGamepad.buttons[15].value;
  71007. }
  71008. };
  71009. Xbox360Pad.prototype.dispose = function () {
  71010. _super.prototype.dispose.call(this);
  71011. this.onButtonDownObservable.clear();
  71012. this.onButtonUpObservable.clear();
  71013. this.onPadDownObservable.clear();
  71014. this.onPadUpObservable.clear();
  71015. };
  71016. return Xbox360Pad;
  71017. }(BABYLON.Gamepad));
  71018. BABYLON.Xbox360Pad = Xbox360Pad;
  71019. })(BABYLON || (BABYLON = {}));
  71020. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71021. var BABYLON;
  71022. (function (BABYLON) {
  71023. /**
  71024. * Defines the types of pose enabled controllers that are supported
  71025. */
  71026. var PoseEnabledControllerType;
  71027. (function (PoseEnabledControllerType) {
  71028. /**
  71029. * HTC Vive
  71030. */
  71031. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71032. /**
  71033. * Oculus Rift
  71034. */
  71035. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71036. /**
  71037. * Windows mixed reality
  71038. */
  71039. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71040. /**
  71041. * Samsung gear VR
  71042. */
  71043. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71044. /**
  71045. * Google Daydream
  71046. */
  71047. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71048. /**
  71049. * Generic
  71050. */
  71051. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71052. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71053. /**
  71054. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71055. */
  71056. var PoseEnabledControllerHelper = /** @class */ (function () {
  71057. function PoseEnabledControllerHelper() {
  71058. }
  71059. /**
  71060. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71061. * @param vrGamepad the gamepad to initialized
  71062. * @returns a vr controller of the type the gamepad identified as
  71063. */
  71064. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71065. // Oculus Touch
  71066. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71067. return new BABYLON.OculusTouchController(vrGamepad);
  71068. }
  71069. // Windows Mixed Reality controllers
  71070. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71071. return new BABYLON.WindowsMotionController(vrGamepad);
  71072. }
  71073. // HTC Vive
  71074. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71075. return new BABYLON.ViveController(vrGamepad);
  71076. }
  71077. // Samsung/Oculus Gear VR
  71078. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  71079. return new BABYLON.GearVRController(vrGamepad);
  71080. }
  71081. // Google Daydream
  71082. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71083. return new BABYLON.DaydreamController(vrGamepad);
  71084. }
  71085. // Generic
  71086. else {
  71087. return new BABYLON.GenericController(vrGamepad);
  71088. }
  71089. };
  71090. return PoseEnabledControllerHelper;
  71091. }());
  71092. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71093. /**
  71094. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71095. */
  71096. var PoseEnabledController = /** @class */ (function (_super) {
  71097. __extends(PoseEnabledController, _super);
  71098. /**
  71099. * Creates a new PoseEnabledController from a gamepad
  71100. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71101. */
  71102. function PoseEnabledController(browserGamepad) {
  71103. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71104. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71105. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71106. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71107. /**
  71108. * The device position in babylon space
  71109. */
  71110. _this.devicePosition = BABYLON.Vector3.Zero();
  71111. /**
  71112. * The device rotation in babylon space
  71113. */
  71114. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71115. /**
  71116. * The scale factor of the device in babylon space
  71117. */
  71118. _this.deviceScaleFactor = 1;
  71119. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71120. /**
  71121. * Internal, matrix used to convert room space to babylon space
  71122. */
  71123. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71124. /**
  71125. * Node to be used when casting a ray from the controller
  71126. */
  71127. _this._pointingPoseNode = null;
  71128. _this._workingMatrix = BABYLON.Matrix.Identity();
  71129. /**
  71130. * @hidden
  71131. */
  71132. _this._meshAttachedObservable = new BABYLON.Observable();
  71133. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71134. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71135. _this.position = BABYLON.Vector3.Zero();
  71136. _this.rotationQuaternion = new BABYLON.Quaternion();
  71137. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71138. _this._calculatedRotation = new BABYLON.Quaternion();
  71139. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71140. return _this;
  71141. }
  71142. /**
  71143. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71144. */
  71145. PoseEnabledController.prototype.update = function () {
  71146. _super.prototype.update.call(this);
  71147. var pose = this.browserGamepad.pose;
  71148. this.updateFromDevice(pose);
  71149. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71150. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71151. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71152. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71153. if (this._mesh) {
  71154. this._mesh.position.copyFrom(this.devicePosition);
  71155. if (this._mesh.rotationQuaternion) {
  71156. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71157. }
  71158. }
  71159. };
  71160. /**
  71161. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71162. * @param poseData raw pose fromthe device
  71163. */
  71164. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71165. if (poseData) {
  71166. this.rawPose = poseData;
  71167. if (poseData.position) {
  71168. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71169. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71170. this._deviceRoomPosition.z *= -1;
  71171. }
  71172. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71173. this._calculatedPosition.addInPlace(this.position);
  71174. }
  71175. var pose = this.rawPose;
  71176. if (poseData.orientation && pose.orientation) {
  71177. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71178. if (this._mesh) {
  71179. if (this._mesh.getScene().useRightHandedSystem) {
  71180. this._deviceRoomRotationQuaternion.z *= -1;
  71181. this._deviceRoomRotationQuaternion.w *= -1;
  71182. }
  71183. else {
  71184. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71185. }
  71186. }
  71187. // if the camera is set, rotate to the camera's rotation
  71188. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71189. }
  71190. }
  71191. };
  71192. /**
  71193. * Attaches a mesh to the controller
  71194. * @param mesh the mesh to be attached
  71195. */
  71196. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71197. if (this._mesh) {
  71198. this._mesh.parent = null;
  71199. }
  71200. this._mesh = mesh;
  71201. if (this._poseControlledCamera) {
  71202. this._mesh.parent = this._poseControlledCamera;
  71203. }
  71204. if (!this._mesh.rotationQuaternion) {
  71205. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71206. }
  71207. this._meshAttachedObservable.notifyObservers(mesh);
  71208. };
  71209. /**
  71210. * Attaches the controllers mesh to a camera
  71211. * @param camera the camera the mesh should be attached to
  71212. */
  71213. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71214. this._poseControlledCamera = camera;
  71215. if (this._mesh) {
  71216. this._mesh.parent = this._poseControlledCamera;
  71217. }
  71218. };
  71219. /**
  71220. * Disposes of the controller
  71221. */
  71222. PoseEnabledController.prototype.dispose = function () {
  71223. if (this._mesh) {
  71224. this._mesh.dispose();
  71225. }
  71226. this._mesh = null;
  71227. _super.prototype.dispose.call(this);
  71228. };
  71229. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71230. /**
  71231. * The mesh that is attached to the controller
  71232. */
  71233. get: function () {
  71234. return this._mesh;
  71235. },
  71236. enumerable: true,
  71237. configurable: true
  71238. });
  71239. /**
  71240. * Gets the ray of the controller in the direction the controller is pointing
  71241. * @param length the length the resulting ray should be
  71242. * @returns a ray in the direction the controller is pointing
  71243. */
  71244. PoseEnabledController.prototype.getForwardRay = function (length) {
  71245. if (length === void 0) { length = 100; }
  71246. if (!this.mesh) {
  71247. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71248. }
  71249. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71250. var origin = m.getTranslation();
  71251. var forward = new BABYLON.Vector3(0, 0, -1);
  71252. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71253. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71254. return new BABYLON.Ray(origin, direction, length);
  71255. };
  71256. /**
  71257. * Name of the child mesh that can be used to cast a ray from the controller
  71258. */
  71259. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71260. return PoseEnabledController;
  71261. }(BABYLON.Gamepad));
  71262. BABYLON.PoseEnabledController = PoseEnabledController;
  71263. })(BABYLON || (BABYLON = {}));
  71264. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71265. var BABYLON;
  71266. (function (BABYLON) {
  71267. /**
  71268. * Defines the WebVRController object that represents controllers tracked in 3D space
  71269. */
  71270. var WebVRController = /** @class */ (function (_super) {
  71271. __extends(WebVRController, _super);
  71272. /**
  71273. * Creates a new WebVRController from a gamepad
  71274. * @param vrGamepad the gamepad that the WebVRController should be created from
  71275. */
  71276. function WebVRController(vrGamepad) {
  71277. var _this = _super.call(this, vrGamepad) || this;
  71278. // Observables
  71279. /**
  71280. * Fired when the trigger state has changed
  71281. */
  71282. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71283. /**
  71284. * Fired when the main button state has changed
  71285. */
  71286. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71287. /**
  71288. * Fired when the secondary button state has changed
  71289. */
  71290. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71291. /**
  71292. * Fired when the pad state has changed
  71293. */
  71294. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71295. /**
  71296. * Fired when controllers stick values have changed
  71297. */
  71298. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71299. /**
  71300. * X and Y axis corrisponding to the controllers joystick
  71301. */
  71302. _this.pad = { x: 0, y: 0 };
  71303. // avoid GC, store state in a tmp object
  71304. _this._changes = {
  71305. pressChanged: false,
  71306. touchChanged: false,
  71307. valueChanged: false,
  71308. changed: false
  71309. };
  71310. _this._buttons = new Array(vrGamepad.buttons.length);
  71311. _this.hand = vrGamepad.hand;
  71312. return _this;
  71313. }
  71314. /**
  71315. * Fired when a controller button's state has changed
  71316. * @param callback the callback containing the button that was modified
  71317. */
  71318. WebVRController.prototype.onButtonStateChange = function (callback) {
  71319. this._onButtonStateChange = callback;
  71320. };
  71321. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71322. /**
  71323. * The default controller model for the controller
  71324. */
  71325. get: function () {
  71326. return this._defaultModel;
  71327. },
  71328. enumerable: true,
  71329. configurable: true
  71330. });
  71331. /**
  71332. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71333. */
  71334. WebVRController.prototype.update = function () {
  71335. _super.prototype.update.call(this);
  71336. for (var index = 0; index < this._buttons.length; index++) {
  71337. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71338. }
  71339. ;
  71340. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71341. this.pad.x = this.leftStick.x;
  71342. this.pad.y = this.leftStick.y;
  71343. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71344. }
  71345. };
  71346. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71347. if (!newState) {
  71348. newState = {
  71349. pressed: false,
  71350. touched: false,
  71351. value: 0
  71352. };
  71353. }
  71354. if (!currentState) {
  71355. this._buttons[buttonIndex] = {
  71356. pressed: newState.pressed,
  71357. touched: newState.touched,
  71358. value: newState.value
  71359. };
  71360. return;
  71361. }
  71362. this._checkChanges(newState, currentState);
  71363. if (this._changes.changed) {
  71364. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71365. this._handleButtonChange(buttonIndex, newState, this._changes);
  71366. }
  71367. this._buttons[buttonIndex].pressed = newState.pressed;
  71368. this._buttons[buttonIndex].touched = newState.touched;
  71369. // oculus triggers are never 0, thou not touched.
  71370. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71371. };
  71372. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71373. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71374. this._changes.touchChanged = newState.touched !== currentState.touched;
  71375. this._changes.valueChanged = newState.value !== currentState.value;
  71376. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71377. return this._changes;
  71378. };
  71379. /**
  71380. * Disposes of th webVRCOntroller
  71381. */
  71382. WebVRController.prototype.dispose = function () {
  71383. _super.prototype.dispose.call(this);
  71384. this.onTriggerStateChangedObservable.clear();
  71385. this.onMainButtonStateChangedObservable.clear();
  71386. this.onSecondaryButtonStateChangedObservable.clear();
  71387. this.onPadStateChangedObservable.clear();
  71388. this.onPadValuesChangedObservable.clear();
  71389. };
  71390. return WebVRController;
  71391. }(BABYLON.PoseEnabledController));
  71392. BABYLON.WebVRController = WebVRController;
  71393. })(BABYLON || (BABYLON = {}));
  71394. //# sourceMappingURL=babylon.webVRController.js.map
  71395. var BABYLON;
  71396. (function (BABYLON) {
  71397. /**
  71398. * Oculus Touch Controller
  71399. */
  71400. var OculusTouchController = /** @class */ (function (_super) {
  71401. __extends(OculusTouchController, _super);
  71402. /**
  71403. * Creates a new OculusTouchController from a gamepad
  71404. * @param vrGamepad the gamepad that the controller should be created from
  71405. */
  71406. function OculusTouchController(vrGamepad) {
  71407. var _this = _super.call(this, vrGamepad) || this;
  71408. /**
  71409. * Fired when the secondary trigger on this controller is modified
  71410. */
  71411. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71412. /**
  71413. * Fired when the thumb rest on this controller is modified
  71414. */
  71415. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71416. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71417. return _this;
  71418. }
  71419. /**
  71420. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71421. * @param scene scene in which to add meshes
  71422. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71423. */
  71424. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71425. var _this = this;
  71426. var meshName;
  71427. // Hand
  71428. if (this.hand === 'left') {
  71429. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71430. }
  71431. else { // Right is the default if no hand is specified
  71432. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71433. }
  71434. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71435. /*
  71436. Parent Mesh name: oculus_touch_left
  71437. - body
  71438. - trigger
  71439. - thumbstick
  71440. - grip
  71441. - button_y
  71442. - button_x
  71443. - button_enter
  71444. */
  71445. _this._defaultModel = newMeshes[1];
  71446. _this.attachToMesh(_this._defaultModel);
  71447. if (meshLoaded) {
  71448. meshLoaded(_this._defaultModel);
  71449. }
  71450. });
  71451. };
  71452. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71453. /**
  71454. * Fired when the A button on this controller is modified
  71455. */
  71456. get: function () {
  71457. if (this.hand === 'right') {
  71458. return this.onMainButtonStateChangedObservable;
  71459. }
  71460. else {
  71461. throw new Error('No A button on left hand');
  71462. }
  71463. },
  71464. enumerable: true,
  71465. configurable: true
  71466. });
  71467. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71468. /**
  71469. * Fired when the B button on this controller is modified
  71470. */
  71471. get: function () {
  71472. if (this.hand === 'right') {
  71473. return this.onSecondaryButtonStateChangedObservable;
  71474. }
  71475. else {
  71476. throw new Error('No B button on left hand');
  71477. }
  71478. },
  71479. enumerable: true,
  71480. configurable: true
  71481. });
  71482. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71483. /**
  71484. * Fired when the X button on this controller is modified
  71485. */
  71486. get: function () {
  71487. if (this.hand === 'left') {
  71488. return this.onMainButtonStateChangedObservable;
  71489. }
  71490. else {
  71491. throw new Error('No X button on right hand');
  71492. }
  71493. },
  71494. enumerable: true,
  71495. configurable: true
  71496. });
  71497. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71498. /**
  71499. * Fired when the Y button on this controller is modified
  71500. */
  71501. get: function () {
  71502. if (this.hand === 'left') {
  71503. return this.onSecondaryButtonStateChangedObservable;
  71504. }
  71505. else {
  71506. throw new Error('No Y button on right hand');
  71507. }
  71508. },
  71509. enumerable: true,
  71510. configurable: true
  71511. });
  71512. /**
  71513. * Called once for each button that changed state since the last frame
  71514. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71515. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71516. * 2) secondary trigger (same)
  71517. * 3) A (right) X (left), touch, pressed = value
  71518. * 4) B / Y
  71519. * 5) thumb rest
  71520. * @param buttonIdx Which button index changed
  71521. * @param state New state of the button
  71522. * @param changes Which properties on the state changed since last frame
  71523. */
  71524. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71525. var notifyObject = state; //{ state: state, changes: changes };
  71526. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71527. switch (buttonIdx) {
  71528. case 0:
  71529. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71530. return;
  71531. case 1: // index trigger
  71532. if (this._defaultModel) {
  71533. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71534. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71535. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71536. }
  71537. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71538. return;
  71539. case 2: // secondary trigger
  71540. if (this._defaultModel) {
  71541. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71542. }
  71543. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71544. return;
  71545. case 3:
  71546. if (this._defaultModel) {
  71547. if (notifyObject.pressed) {
  71548. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71549. }
  71550. else {
  71551. (this._defaultModel.getChildren()[1]).position.y = 0;
  71552. }
  71553. }
  71554. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71555. return;
  71556. case 4:
  71557. if (this._defaultModel) {
  71558. if (notifyObject.pressed) {
  71559. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71560. }
  71561. else {
  71562. (this._defaultModel.getChildren()[2]).position.y = 0;
  71563. }
  71564. }
  71565. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71566. return;
  71567. case 5:
  71568. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71569. return;
  71570. }
  71571. };
  71572. /**
  71573. * Base Url for the controller model.
  71574. */
  71575. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71576. /**
  71577. * File name for the left controller model.
  71578. */
  71579. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71580. /**
  71581. * File name for the right controller model.
  71582. */
  71583. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71584. return OculusTouchController;
  71585. }(BABYLON.WebVRController));
  71586. BABYLON.OculusTouchController = OculusTouchController;
  71587. })(BABYLON || (BABYLON = {}));
  71588. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71589. var BABYLON;
  71590. (function (BABYLON) {
  71591. /**
  71592. * Vive Controller
  71593. */
  71594. var ViveController = /** @class */ (function (_super) {
  71595. __extends(ViveController, _super);
  71596. /**
  71597. * Creates a new ViveController from a gamepad
  71598. * @param vrGamepad the gamepad that the controller should be created from
  71599. */
  71600. function ViveController(vrGamepad) {
  71601. var _this = _super.call(this, vrGamepad) || this;
  71602. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71603. _this._invertLeftStickY = true;
  71604. return _this;
  71605. }
  71606. /**
  71607. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71608. * @param scene scene in which to add meshes
  71609. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71610. */
  71611. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71612. var _this = this;
  71613. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71614. /*
  71615. Parent Mesh name: ViveWand
  71616. - body
  71617. - r_gripper
  71618. - l_gripper
  71619. - menu_button
  71620. - system_button
  71621. - trackpad
  71622. - trigger
  71623. - LED
  71624. */
  71625. _this._defaultModel = newMeshes[1];
  71626. _this.attachToMesh(_this._defaultModel);
  71627. if (meshLoaded) {
  71628. meshLoaded(_this._defaultModel);
  71629. }
  71630. });
  71631. };
  71632. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71633. /**
  71634. * Fired when the left button on this controller is modified
  71635. */
  71636. get: function () {
  71637. return this.onMainButtonStateChangedObservable;
  71638. },
  71639. enumerable: true,
  71640. configurable: true
  71641. });
  71642. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71643. /**
  71644. * Fired when the right button on this controller is modified
  71645. */
  71646. get: function () {
  71647. return this.onMainButtonStateChangedObservable;
  71648. },
  71649. enumerable: true,
  71650. configurable: true
  71651. });
  71652. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71653. /**
  71654. * Fired when the menu button on this controller is modified
  71655. */
  71656. get: function () {
  71657. return this.onSecondaryButtonStateChangedObservable;
  71658. },
  71659. enumerable: true,
  71660. configurable: true
  71661. });
  71662. /**
  71663. * Called once for each button that changed state since the last frame
  71664. * Vive mapping:
  71665. * 0: touchpad
  71666. * 1: trigger
  71667. * 2: left AND right buttons
  71668. * 3: menu button
  71669. * @param buttonIdx Which button index changed
  71670. * @param state New state of the button
  71671. * @param changes Which properties on the state changed since last frame
  71672. */
  71673. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71674. var notifyObject = state; //{ state: state, changes: changes };
  71675. switch (buttonIdx) {
  71676. case 0:
  71677. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71678. return;
  71679. case 1: // index trigger
  71680. if (this._defaultModel) {
  71681. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71682. }
  71683. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71684. return;
  71685. case 2: // left AND right button
  71686. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71687. return;
  71688. case 3:
  71689. if (this._defaultModel) {
  71690. if (notifyObject.pressed) {
  71691. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71692. }
  71693. else {
  71694. (this._defaultModel.getChildren()[2]).position.y = 0;
  71695. }
  71696. }
  71697. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71698. return;
  71699. }
  71700. };
  71701. /**
  71702. * Base Url for the controller model.
  71703. */
  71704. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71705. /**
  71706. * File name for the controller model.
  71707. */
  71708. ViveController.MODEL_FILENAME = 'wand.babylon';
  71709. return ViveController;
  71710. }(BABYLON.WebVRController));
  71711. BABYLON.ViveController = ViveController;
  71712. })(BABYLON || (BABYLON = {}));
  71713. //# sourceMappingURL=babylon.viveController.js.map
  71714. var BABYLON;
  71715. (function (BABYLON) {
  71716. /**
  71717. * Generic Controller
  71718. */
  71719. var GenericController = /** @class */ (function (_super) {
  71720. __extends(GenericController, _super);
  71721. /**
  71722. * Creates a new GenericController from a gamepad
  71723. * @param vrGamepad the gamepad that the controller should be created from
  71724. */
  71725. function GenericController(vrGamepad) {
  71726. return _super.call(this, vrGamepad) || this;
  71727. }
  71728. /**
  71729. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71730. * @param scene scene in which to add meshes
  71731. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71732. */
  71733. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71734. var _this = this;
  71735. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71736. _this._defaultModel = newMeshes[1];
  71737. _this.attachToMesh(_this._defaultModel);
  71738. if (meshLoaded) {
  71739. meshLoaded(_this._defaultModel);
  71740. }
  71741. });
  71742. };
  71743. /**
  71744. * Called once for each button that changed state since the last frame
  71745. * @param buttonIdx Which button index changed
  71746. * @param state New state of the button
  71747. * @param changes Which properties on the state changed since last frame
  71748. */
  71749. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71750. console.log("Button id: " + buttonIdx + "state: ");
  71751. console.dir(state);
  71752. };
  71753. /**
  71754. * Base Url for the controller model.
  71755. */
  71756. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71757. /**
  71758. * File name for the controller model.
  71759. */
  71760. GenericController.MODEL_FILENAME = 'generic.babylon';
  71761. return GenericController;
  71762. }(BABYLON.WebVRController));
  71763. BABYLON.GenericController = GenericController;
  71764. })(BABYLON || (BABYLON = {}));
  71765. //# sourceMappingURL=babylon.genericController.js.map
  71766. var BABYLON;
  71767. (function (BABYLON) {
  71768. /**
  71769. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71770. */
  71771. var LoadedMeshInfo = /** @class */ (function () {
  71772. function LoadedMeshInfo() {
  71773. /**
  71774. * Map of the button meshes contained in the controller
  71775. */
  71776. this.buttonMeshes = {};
  71777. /**
  71778. * Map of the axis meshes contained in the controller
  71779. */
  71780. this.axisMeshes = {};
  71781. }
  71782. return LoadedMeshInfo;
  71783. }());
  71784. /**
  71785. * Defines the WindowsMotionController object that the state of the windows motion controller
  71786. */
  71787. var WindowsMotionController = /** @class */ (function (_super) {
  71788. __extends(WindowsMotionController, _super);
  71789. /**
  71790. * Creates a new WindowsMotionController from a gamepad
  71791. * @param vrGamepad the gamepad that the controller should be created from
  71792. */
  71793. function WindowsMotionController(vrGamepad) {
  71794. var _this = _super.call(this, vrGamepad) || this;
  71795. _this._mapping = {
  71796. // Semantic button names
  71797. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71798. // A mapping of the button name to glTF model node name
  71799. // that should be transformed by button value.
  71800. buttonMeshNames: {
  71801. 'trigger': 'SELECT',
  71802. 'menu': 'MENU',
  71803. 'grip': 'GRASP',
  71804. 'thumbstick': 'THUMBSTICK_PRESS',
  71805. 'trackpad': 'TOUCHPAD_PRESS'
  71806. },
  71807. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71808. buttonObservableNames: {
  71809. 'trigger': 'onTriggerStateChangedObservable',
  71810. 'menu': 'onSecondaryButtonStateChangedObservable',
  71811. 'grip': 'onMainButtonStateChangedObservable',
  71812. 'thumbstick': 'onPadStateChangedObservable',
  71813. 'trackpad': 'onTrackpadChangedObservable'
  71814. },
  71815. // A mapping of the axis name to glTF model node name
  71816. // that should be transformed by axis value.
  71817. // This array mirrors the browserGamepad.axes array, such that
  71818. // the mesh corresponding to axis 0 is in this array index 0.
  71819. axisMeshNames: [
  71820. 'THUMBSTICK_X',
  71821. 'THUMBSTICK_Y',
  71822. 'TOUCHPAD_TOUCH_X',
  71823. 'TOUCHPAD_TOUCH_Y'
  71824. ],
  71825. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71826. };
  71827. /**
  71828. * Fired when the trackpad on this controller is clicked
  71829. */
  71830. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71831. /**
  71832. * Fired when the trackpad on this controller is modified
  71833. */
  71834. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71835. /**
  71836. * The current x and y values of this controller's trackpad
  71837. */
  71838. _this.trackpad = { x: 0, y: 0 };
  71839. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71840. _this._loadedMeshInfo = null;
  71841. return _this;
  71842. }
  71843. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71844. /**
  71845. * Fired when the trigger on this controller is modified
  71846. */
  71847. get: function () {
  71848. return this.onTriggerStateChangedObservable;
  71849. },
  71850. enumerable: true,
  71851. configurable: true
  71852. });
  71853. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71854. /**
  71855. * Fired when the menu button on this controller is modified
  71856. */
  71857. get: function () {
  71858. return this.onSecondaryButtonStateChangedObservable;
  71859. },
  71860. enumerable: true,
  71861. configurable: true
  71862. });
  71863. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71864. /**
  71865. * Fired when the grip button on this controller is modified
  71866. */
  71867. get: function () {
  71868. return this.onMainButtonStateChangedObservable;
  71869. },
  71870. enumerable: true,
  71871. configurable: true
  71872. });
  71873. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71874. /**
  71875. * Fired when the thumbstick button on this controller is modified
  71876. */
  71877. get: function () {
  71878. return this.onPadStateChangedObservable;
  71879. },
  71880. enumerable: true,
  71881. configurable: true
  71882. });
  71883. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71884. /**
  71885. * Fired when the touchpad button on this controller is modified
  71886. */
  71887. get: function () {
  71888. return this.onTrackpadChangedObservable;
  71889. },
  71890. enumerable: true,
  71891. configurable: true
  71892. });
  71893. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71894. /**
  71895. * Fired when the touchpad values on this controller are modified
  71896. */
  71897. get: function () {
  71898. return this.onTrackpadValuesChangedObservable;
  71899. },
  71900. enumerable: true,
  71901. configurable: true
  71902. });
  71903. /**
  71904. * Called once per frame by the engine.
  71905. */
  71906. WindowsMotionController.prototype.update = function () {
  71907. _super.prototype.update.call(this);
  71908. if (this.browserGamepad.axes) {
  71909. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71910. this.trackpad.x = this.browserGamepad["axes"][2];
  71911. this.trackpad.y = this.browserGamepad["axes"][3];
  71912. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71913. }
  71914. // Only need to animate axes if there is a loaded mesh
  71915. if (this._loadedMeshInfo) {
  71916. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71917. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71918. }
  71919. }
  71920. }
  71921. };
  71922. /**
  71923. * Called once for each button that changed state since the last frame
  71924. * @param buttonIdx Which button index changed
  71925. * @param state New state of the button
  71926. * @param changes Which properties on the state changed since last frame
  71927. */
  71928. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71929. var buttonName = this._mapping.buttons[buttonIdx];
  71930. if (!buttonName) {
  71931. return;
  71932. }
  71933. // Only emit events for buttons that we know how to map from index to name
  71934. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71935. if (observable) {
  71936. observable.notifyObservers(state);
  71937. }
  71938. this._lerpButtonTransform(buttonName, state.value);
  71939. };
  71940. /**
  71941. * Moves the buttons on the controller mesh based on their current state
  71942. * @param buttonName the name of the button to move
  71943. * @param buttonValue the value of the button which determines the buttons new position
  71944. */
  71945. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71946. // If there is no loaded mesh, there is nothing to transform.
  71947. if (!this._loadedMeshInfo) {
  71948. return;
  71949. }
  71950. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71951. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71952. return;
  71953. }
  71954. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71955. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71956. };
  71957. /**
  71958. * Moves the axis on the controller mesh based on its current state
  71959. * @param axis the index of the axis
  71960. * @param axisValue the value of the axis which determines the meshes new position
  71961. * @hidden
  71962. */
  71963. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71964. if (!this._loadedMeshInfo) {
  71965. return;
  71966. }
  71967. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71968. if (!meshInfo) {
  71969. return;
  71970. }
  71971. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71972. return;
  71973. }
  71974. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71975. var lerpValue = axisValue * 0.5 + 0.5;
  71976. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71977. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71978. };
  71979. /**
  71980. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71981. * @param scene scene in which to add meshes
  71982. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71983. */
  71984. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71985. var _this = this;
  71986. if (forceDefault === void 0) { forceDefault = false; }
  71987. var path;
  71988. var filename;
  71989. // Checking if GLB loader is present
  71990. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71991. // Determine the device specific folder based on the ID suffix
  71992. var device = 'default';
  71993. if (this.id && !forceDefault) {
  71994. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71995. device = ((match && match[0]) || device);
  71996. }
  71997. // Hand
  71998. if (this.hand === 'left') {
  71999. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72000. }
  72001. else { // Right is the default if no hand is specified
  72002. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72003. }
  72004. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72005. }
  72006. else {
  72007. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72008. path = BABYLON.GenericController.MODEL_BASE_URL;
  72009. filename = BABYLON.GenericController.MODEL_FILENAME;
  72010. }
  72011. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72012. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72013. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72014. if (!_this._loadedMeshInfo) {
  72015. return;
  72016. }
  72017. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72018. _this.attachToMesh(_this._defaultModel);
  72019. if (meshLoaded) {
  72020. meshLoaded(_this._defaultModel);
  72021. }
  72022. }, null, function (scene, message) {
  72023. BABYLON.Tools.Log(message);
  72024. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72025. if (!forceDefault) {
  72026. _this.initControllerMesh(scene, meshLoaded, true);
  72027. }
  72028. });
  72029. };
  72030. /**
  72031. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72032. * can be transformed by button presses and axes values, based on this._mapping.
  72033. *
  72034. * @param scene scene in which the meshes exist
  72035. * @param meshes list of meshes that make up the controller model to process
  72036. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72037. */
  72038. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72039. var loadedMeshInfo = null;
  72040. // Create a new mesh to contain the glTF hierarchy
  72041. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72042. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72043. var childMesh = null;
  72044. for (var i = 0; i < meshes.length; i++) {
  72045. var mesh = meshes[i];
  72046. if (!mesh.parent) {
  72047. // Exclude controller meshes from picking results
  72048. mesh.isPickable = false;
  72049. // Handle root node, attach to the new parentMesh
  72050. childMesh = mesh;
  72051. break;
  72052. }
  72053. }
  72054. if (childMesh) {
  72055. childMesh.setParent(parentMesh);
  72056. // Create our mesh info. Note that this method will always return non-null.
  72057. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72058. }
  72059. else {
  72060. BABYLON.Tools.Warn('Could not find root node in model file.');
  72061. }
  72062. return loadedMeshInfo;
  72063. };
  72064. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72065. var loadedMeshInfo = new LoadedMeshInfo();
  72066. var i;
  72067. loadedMeshInfo.rootNode = rootNode;
  72068. // Reset the caches
  72069. loadedMeshInfo.buttonMeshes = {};
  72070. loadedMeshInfo.axisMeshes = {};
  72071. // Button Meshes
  72072. for (i = 0; i < this._mapping.buttons.length; i++) {
  72073. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72074. if (!buttonMeshName) {
  72075. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72076. continue;
  72077. }
  72078. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72079. if (!buttonMesh) {
  72080. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72081. continue;
  72082. }
  72083. var buttonMeshInfo = {
  72084. index: i,
  72085. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72086. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72087. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72088. };
  72089. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72090. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72091. }
  72092. else {
  72093. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72094. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72095. '(VALUE: ' + !!buttonMeshInfo.value +
  72096. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72097. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72098. ')');
  72099. }
  72100. }
  72101. // Axis Meshes
  72102. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72103. var axisMeshName = this._mapping.axisMeshNames[i];
  72104. if (!axisMeshName) {
  72105. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72106. continue;
  72107. }
  72108. var axisMesh = getChildByName(rootNode, axisMeshName);
  72109. if (!axisMesh) {
  72110. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72111. continue;
  72112. }
  72113. var axisMeshInfo = {
  72114. index: i,
  72115. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72116. min: getImmediateChildByName(axisMesh, 'MIN'),
  72117. max: getImmediateChildByName(axisMesh, 'MAX')
  72118. };
  72119. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72120. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72121. }
  72122. else {
  72123. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72124. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72125. '(VALUE: ' + !!axisMeshInfo.value +
  72126. ', MIN: ' + !!axisMeshInfo.min +
  72127. ', MAX:' + !!axisMeshInfo.max +
  72128. ')');
  72129. }
  72130. }
  72131. // Pointing Ray
  72132. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72133. if (!loadedMeshInfo.pointingPoseNode) {
  72134. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72135. }
  72136. return loadedMeshInfo;
  72137. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72138. function getChildByName(node, name) {
  72139. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72140. }
  72141. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72142. function getImmediateChildByName(node, name) {
  72143. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72144. }
  72145. };
  72146. /**
  72147. * Gets the ray of the controller in the direction the controller is pointing
  72148. * @param length the length the resulting ray should be
  72149. * @returns a ray in the direction the controller is pointing
  72150. */
  72151. WindowsMotionController.prototype.getForwardRay = function (length) {
  72152. if (length === void 0) { length = 100; }
  72153. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72154. return _super.prototype.getForwardRay.call(this, length);
  72155. }
  72156. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72157. var origin = m.getTranslation();
  72158. var forward = new BABYLON.Vector3(0, 0, -1);
  72159. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72160. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72161. return new BABYLON.Ray(origin, direction, length);
  72162. };
  72163. /**
  72164. * Disposes of the controller
  72165. */
  72166. WindowsMotionController.prototype.dispose = function () {
  72167. _super.prototype.dispose.call(this);
  72168. this.onTrackpadChangedObservable.clear();
  72169. };
  72170. /**
  72171. * The base url used to load the left and right controller models
  72172. */
  72173. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72174. /**
  72175. * The name of the left controller model file
  72176. */
  72177. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72178. /**
  72179. * The name of the right controller model file
  72180. */
  72181. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72182. /**
  72183. * The controller name prefix for this controller type
  72184. */
  72185. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72186. /**
  72187. * The controller id pattern for this controller type
  72188. */
  72189. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72190. return WindowsMotionController;
  72191. }(BABYLON.WebVRController));
  72192. BABYLON.WindowsMotionController = WindowsMotionController;
  72193. })(BABYLON || (BABYLON = {}));
  72194. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72195. var BABYLON;
  72196. (function (BABYLON) {
  72197. /**
  72198. * Gear VR Controller
  72199. */
  72200. var GearVRController = /** @class */ (function (_super) {
  72201. __extends(GearVRController, _super);
  72202. /**
  72203. * Creates a new GearVRController from a gamepad
  72204. * @param vrGamepad the gamepad that the controller should be created from
  72205. */
  72206. function GearVRController(vrGamepad) {
  72207. var _this = _super.call(this, vrGamepad) || this;
  72208. _this._buttonIndexToObservableNameMap = [
  72209. 'onTrackpadChangedObservable',
  72210. 'onTriggerStateChangedObservable' // Trigger
  72211. ];
  72212. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72213. return _this;
  72214. }
  72215. /**
  72216. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72217. * @param scene scene in which to add meshes
  72218. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72219. */
  72220. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72221. var _this = this;
  72222. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72223. _this._defaultModel = newMeshes[1];
  72224. _this.attachToMesh(_this._defaultModel);
  72225. if (meshLoaded) {
  72226. meshLoaded(_this._defaultModel);
  72227. }
  72228. });
  72229. };
  72230. /**
  72231. * Called once for each button that changed state since the last frame
  72232. * @param buttonIdx Which button index changed
  72233. * @param state New state of the button
  72234. * @param changes Which properties on the state changed since last frame
  72235. */
  72236. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72237. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72238. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72239. // Only emit events for buttons that we know how to map from index to observable
  72240. var observable = this[observableName];
  72241. if (observable) {
  72242. observable.notifyObservers(state);
  72243. }
  72244. }
  72245. };
  72246. /**
  72247. * Base Url for the controller model.
  72248. */
  72249. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72250. /**
  72251. * File name for the controller model.
  72252. */
  72253. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72254. /**
  72255. * Gamepad Id prefix used to identify this controller.
  72256. */
  72257. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72258. return GearVRController;
  72259. }(BABYLON.WebVRController));
  72260. BABYLON.GearVRController = GearVRController;
  72261. })(BABYLON || (BABYLON = {}));
  72262. //# sourceMappingURL=babylon.gearVRController.js.map
  72263. var BABYLON;
  72264. (function (BABYLON) {
  72265. /**
  72266. * Google Daydream controller
  72267. */
  72268. var DaydreamController = /** @class */ (function (_super) {
  72269. __extends(DaydreamController, _super);
  72270. /**
  72271. * Creates a new DaydreamController from a gamepad
  72272. * @param vrGamepad the gamepad that the controller should be created from
  72273. */
  72274. function DaydreamController(vrGamepad) {
  72275. var _this = _super.call(this, vrGamepad) || this;
  72276. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72277. return _this;
  72278. }
  72279. /**
  72280. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72281. * @param scene scene in which to add meshes
  72282. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72283. */
  72284. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72285. var _this = this;
  72286. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72287. _this._defaultModel = newMeshes[1];
  72288. _this.attachToMesh(_this._defaultModel);
  72289. if (meshLoaded) {
  72290. meshLoaded(_this._defaultModel);
  72291. }
  72292. });
  72293. };
  72294. /**
  72295. * Called once for each button that changed state since the last frame
  72296. * @param buttonIdx Which button index changed
  72297. * @param state New state of the button
  72298. * @param changes Which properties on the state changed since last frame
  72299. */
  72300. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72301. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72302. if (buttonIdx === 0) {
  72303. var observable = this.onTriggerStateChangedObservable;
  72304. if (observable) {
  72305. observable.notifyObservers(state);
  72306. }
  72307. }
  72308. else {
  72309. // If the app or home buttons are ever made available
  72310. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72311. }
  72312. };
  72313. /**
  72314. * Base Url for the controller model.
  72315. */
  72316. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72317. /**
  72318. * File name for the controller model.
  72319. */
  72320. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72321. /**
  72322. * Gamepad Id prefix used to identify Daydream Controller.
  72323. */
  72324. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72325. return DaydreamController;
  72326. }(BABYLON.WebVRController));
  72327. BABYLON.DaydreamController = DaydreamController;
  72328. })(BABYLON || (BABYLON = {}));
  72329. //# sourceMappingURL=babylon.daydreamController.js.map
  72330. var BABYLON;
  72331. (function (BABYLON) {
  72332. var FollowCamera = /** @class */ (function (_super) {
  72333. __extends(FollowCamera, _super);
  72334. function FollowCamera(name, position, scene, lockedTarget) {
  72335. if (lockedTarget === void 0) { lockedTarget = null; }
  72336. var _this = _super.call(this, name, position, scene) || this;
  72337. _this.radius = 12;
  72338. _this.rotationOffset = 0;
  72339. _this.heightOffset = 4;
  72340. _this.cameraAcceleration = 0.05;
  72341. _this.maxCameraSpeed = 20;
  72342. _this.lockedTarget = lockedTarget;
  72343. return _this;
  72344. }
  72345. FollowCamera.prototype.getRadians = function (degrees) {
  72346. return degrees * Math.PI / 180;
  72347. };
  72348. FollowCamera.prototype.follow = function (cameraTarget) {
  72349. if (!cameraTarget)
  72350. return;
  72351. var yRotation;
  72352. if (cameraTarget.rotationQuaternion) {
  72353. var rotMatrix = new BABYLON.Matrix();
  72354. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72355. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72356. }
  72357. else {
  72358. yRotation = cameraTarget.rotation.y;
  72359. }
  72360. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72361. var targetPosition = cameraTarget.getAbsolutePosition();
  72362. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72363. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72364. var dx = targetX - this.position.x;
  72365. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72366. var dz = (targetZ) - this.position.z;
  72367. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72368. var vy = dy * this.cameraAcceleration;
  72369. var vz = dz * this.cameraAcceleration * 2;
  72370. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72371. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72372. }
  72373. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72374. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72375. }
  72376. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72377. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72378. }
  72379. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72380. this.setTarget(targetPosition);
  72381. };
  72382. FollowCamera.prototype._checkInputs = function () {
  72383. _super.prototype._checkInputs.call(this);
  72384. if (this.lockedTarget) {
  72385. this.follow(this.lockedTarget);
  72386. }
  72387. };
  72388. FollowCamera.prototype.getClassName = function () {
  72389. return "FollowCamera";
  72390. };
  72391. __decorate([
  72392. BABYLON.serialize()
  72393. ], FollowCamera.prototype, "radius", void 0);
  72394. __decorate([
  72395. BABYLON.serialize()
  72396. ], FollowCamera.prototype, "rotationOffset", void 0);
  72397. __decorate([
  72398. BABYLON.serialize()
  72399. ], FollowCamera.prototype, "heightOffset", void 0);
  72400. __decorate([
  72401. BABYLON.serialize()
  72402. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72403. __decorate([
  72404. BABYLON.serialize()
  72405. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72406. __decorate([
  72407. BABYLON.serializeAsMeshReference("lockedTargetId")
  72408. ], FollowCamera.prototype, "lockedTarget", void 0);
  72409. return FollowCamera;
  72410. }(BABYLON.TargetCamera));
  72411. BABYLON.FollowCamera = FollowCamera;
  72412. var ArcFollowCamera = /** @class */ (function (_super) {
  72413. __extends(ArcFollowCamera, _super);
  72414. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72415. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72416. _this.alpha = alpha;
  72417. _this.beta = beta;
  72418. _this.radius = radius;
  72419. _this.target = target;
  72420. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72421. _this.follow();
  72422. return _this;
  72423. }
  72424. ArcFollowCamera.prototype.follow = function () {
  72425. if (!this.target) {
  72426. return;
  72427. }
  72428. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72429. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72430. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72431. var targetPosition = this.target.getAbsolutePosition();
  72432. this.position = targetPosition.add(this._cartesianCoordinates);
  72433. this.setTarget(targetPosition);
  72434. };
  72435. ArcFollowCamera.prototype._checkInputs = function () {
  72436. _super.prototype._checkInputs.call(this);
  72437. this.follow();
  72438. };
  72439. ArcFollowCamera.prototype.getClassName = function () {
  72440. return "ArcFollowCamera";
  72441. };
  72442. return ArcFollowCamera;
  72443. }(BABYLON.TargetCamera));
  72444. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72445. })(BABYLON || (BABYLON = {}));
  72446. //# sourceMappingURL=babylon.followCamera.js.map
  72447. var BABYLON;
  72448. (function (BABYLON) {
  72449. // We're mainly based on the logic defined into the FreeCamera code
  72450. var UniversalCamera = /** @class */ (function (_super) {
  72451. __extends(UniversalCamera, _super);
  72452. //-- end properties for backward compatibility for inputs
  72453. function UniversalCamera(name, position, scene) {
  72454. var _this = _super.call(this, name, position, scene) || this;
  72455. _this.inputs.addGamepad();
  72456. return _this;
  72457. }
  72458. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72459. //-- Begin properties for backward compatibility for inputs
  72460. get: function () {
  72461. var gamepad = this.inputs.attached["gamepad"];
  72462. if (gamepad)
  72463. return gamepad.gamepadAngularSensibility;
  72464. return 0;
  72465. },
  72466. set: function (value) {
  72467. var gamepad = this.inputs.attached["gamepad"];
  72468. if (gamepad)
  72469. gamepad.gamepadAngularSensibility = value;
  72470. },
  72471. enumerable: true,
  72472. configurable: true
  72473. });
  72474. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72475. get: function () {
  72476. var gamepad = this.inputs.attached["gamepad"];
  72477. if (gamepad)
  72478. return gamepad.gamepadMoveSensibility;
  72479. return 0;
  72480. },
  72481. set: function (value) {
  72482. var gamepad = this.inputs.attached["gamepad"];
  72483. if (gamepad)
  72484. gamepad.gamepadMoveSensibility = value;
  72485. },
  72486. enumerable: true,
  72487. configurable: true
  72488. });
  72489. UniversalCamera.prototype.getClassName = function () {
  72490. return "UniversalCamera";
  72491. };
  72492. return UniversalCamera;
  72493. }(BABYLON.TouchCamera));
  72494. BABYLON.UniversalCamera = UniversalCamera;
  72495. })(BABYLON || (BABYLON = {}));
  72496. //# sourceMappingURL=babylon.universalCamera.js.map
  72497. var BABYLON;
  72498. (function (BABYLON) {
  72499. // We're mainly based on the logic defined into the FreeCamera code
  72500. var GamepadCamera = /** @class */ (function (_super) {
  72501. __extends(GamepadCamera, _super);
  72502. //-- end properties for backward compatibility for inputs
  72503. function GamepadCamera(name, position, scene) {
  72504. return _super.call(this, name, position, scene) || this;
  72505. }
  72506. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72507. //-- Begin properties for backward compatibility for inputs
  72508. get: function () {
  72509. var gamepad = this.inputs.attached["gamepad"];
  72510. if (gamepad)
  72511. return gamepad.gamepadAngularSensibility;
  72512. return 0;
  72513. },
  72514. set: function (value) {
  72515. var gamepad = this.inputs.attached["gamepad"];
  72516. if (gamepad)
  72517. gamepad.gamepadAngularSensibility = value;
  72518. },
  72519. enumerable: true,
  72520. configurable: true
  72521. });
  72522. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72523. get: function () {
  72524. var gamepad = this.inputs.attached["gamepad"];
  72525. if (gamepad)
  72526. return gamepad.gamepadMoveSensibility;
  72527. return 0;
  72528. },
  72529. set: function (value) {
  72530. var gamepad = this.inputs.attached["gamepad"];
  72531. if (gamepad)
  72532. gamepad.gamepadMoveSensibility = value;
  72533. },
  72534. enumerable: true,
  72535. configurable: true
  72536. });
  72537. GamepadCamera.prototype.getClassName = function () {
  72538. return "GamepadCamera";
  72539. };
  72540. return GamepadCamera;
  72541. }(BABYLON.UniversalCamera));
  72542. BABYLON.GamepadCamera = GamepadCamera;
  72543. })(BABYLON || (BABYLON = {}));
  72544. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72545. var BABYLON;
  72546. (function (BABYLON) {
  72547. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72548. function PostProcessRenderPipelineManager() {
  72549. this._renderPipelines = {};
  72550. }
  72551. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72552. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72553. };
  72554. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72555. if (unique === void 0) { unique = false; }
  72556. var renderPipeline = this._renderPipelines[renderPipelineName];
  72557. if (!renderPipeline) {
  72558. return;
  72559. }
  72560. renderPipeline._attachCameras(cameras, unique);
  72561. };
  72562. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72563. var renderPipeline = this._renderPipelines[renderPipelineName];
  72564. if (!renderPipeline) {
  72565. return;
  72566. }
  72567. renderPipeline._detachCameras(cameras);
  72568. };
  72569. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72570. var renderPipeline = this._renderPipelines[renderPipelineName];
  72571. if (!renderPipeline) {
  72572. return;
  72573. }
  72574. renderPipeline._enableEffect(renderEffectName, cameras);
  72575. };
  72576. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72577. var renderPipeline = this._renderPipelines[renderPipelineName];
  72578. if (!renderPipeline) {
  72579. return;
  72580. }
  72581. renderPipeline._disableEffect(renderEffectName, cameras);
  72582. };
  72583. PostProcessRenderPipelineManager.prototype.update = function () {
  72584. for (var renderPipelineName in this._renderPipelines) {
  72585. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72586. var pipeline = this._renderPipelines[renderPipelineName];
  72587. if (!pipeline.isSupported) {
  72588. pipeline.dispose();
  72589. delete this._renderPipelines[renderPipelineName];
  72590. }
  72591. else {
  72592. pipeline._update();
  72593. }
  72594. }
  72595. }
  72596. };
  72597. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72598. for (var renderPipelineName in this._renderPipelines) {
  72599. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72600. var pipeline = this._renderPipelines[renderPipelineName];
  72601. pipeline._rebuild();
  72602. }
  72603. }
  72604. };
  72605. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72606. for (var renderPipelineName in this._renderPipelines) {
  72607. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72608. var pipeline = this._renderPipelines[renderPipelineName];
  72609. pipeline.dispose();
  72610. }
  72611. }
  72612. };
  72613. return PostProcessRenderPipelineManager;
  72614. }());
  72615. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72616. })(BABYLON || (BABYLON = {}));
  72617. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72618. var BABYLON;
  72619. (function (BABYLON) {
  72620. /**
  72621. * This represents a set of one or more post processes in Babylon.
  72622. * A post process can be used to apply a shader to a texture after it is rendered.
  72623. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72624. */
  72625. var PostProcessRenderEffect = /** @class */ (function () {
  72626. /**
  72627. * Instantiates a post process render effect.
  72628. * A post process can be used to apply a shader to a texture after it is rendered.
  72629. * @param engine The engine the effect is tied to
  72630. * @param name The name of the effect
  72631. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72632. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72633. */
  72634. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72635. this._name = name;
  72636. this._singleInstance = singleInstance || true;
  72637. this._getPostProcesses = getPostProcesses;
  72638. this._cameras = {};
  72639. this._indicesForCamera = {};
  72640. this._postProcesses = {};
  72641. }
  72642. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72643. /**
  72644. * Checks if all the post processes in the effect are supported.
  72645. */
  72646. get: function () {
  72647. for (var index in this._postProcesses) {
  72648. if (this._postProcesses.hasOwnProperty(index)) {
  72649. var pps = this._postProcesses[index];
  72650. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72651. if (!pps[ppIndex].isSupported) {
  72652. return false;
  72653. }
  72654. }
  72655. }
  72656. }
  72657. return true;
  72658. },
  72659. enumerable: true,
  72660. configurable: true
  72661. });
  72662. /**
  72663. * Updates the current state of the effect
  72664. */
  72665. PostProcessRenderEffect.prototype._update = function () {
  72666. };
  72667. /**
  72668. * Attaches the effect on cameras
  72669. * @param cameras The camera to attach to.
  72670. */
  72671. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72672. var _this = this;
  72673. var cameraKey;
  72674. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72675. if (!cams) {
  72676. return;
  72677. }
  72678. for (var i = 0; i < cams.length; i++) {
  72679. var camera = cams[i];
  72680. var cameraName = camera.name;
  72681. if (this._singleInstance) {
  72682. cameraKey = 0;
  72683. }
  72684. else {
  72685. cameraKey = cameraName;
  72686. }
  72687. if (!this._postProcesses[cameraKey]) {
  72688. var postProcess = this._getPostProcesses();
  72689. if (postProcess) {
  72690. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72691. }
  72692. }
  72693. if (!this._indicesForCamera[cameraName]) {
  72694. this._indicesForCamera[cameraName] = [];
  72695. }
  72696. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72697. var index = camera.attachPostProcess(postProcess);
  72698. _this._indicesForCamera[cameraName].push(index);
  72699. });
  72700. if (!this._cameras[cameraName]) {
  72701. this._cameras[cameraName] = camera;
  72702. }
  72703. }
  72704. };
  72705. /**
  72706. * Detatches the effect on cameras
  72707. * @param cameras The camera to detatch from.
  72708. */
  72709. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72710. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72711. if (!cams) {
  72712. return;
  72713. }
  72714. for (var i = 0; i < cams.length; i++) {
  72715. var camera = cams[i];
  72716. var cameraName = camera.name;
  72717. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72718. camera.detachPostProcess(postProcess);
  72719. });
  72720. if (this._cameras[cameraName]) {
  72721. //this._indicesForCamera.splice(index, 1);
  72722. this._cameras[cameraName] = null;
  72723. }
  72724. }
  72725. };
  72726. /**
  72727. * Enables the effect on given cameras
  72728. * @param cameras The camera to enable.
  72729. */
  72730. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72731. var _this = this;
  72732. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72733. if (!cams) {
  72734. return;
  72735. }
  72736. for (var i = 0; i < cams.length; i++) {
  72737. var camera = cams[i];
  72738. var cameraName = camera.name;
  72739. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72740. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72741. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72742. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72743. });
  72744. }
  72745. }
  72746. }
  72747. };
  72748. /**
  72749. * Disables the effect on the given cameras
  72750. * @param cameras The camera to disable.
  72751. */
  72752. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72753. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72754. if (!cams) {
  72755. return;
  72756. }
  72757. for (var i = 0; i < cams.length; i++) {
  72758. var camera = cams[i];
  72759. var cameraName = camera.name;
  72760. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72761. camera.detachPostProcess(postProcess);
  72762. });
  72763. }
  72764. };
  72765. /**
  72766. * Gets a list of the post processes contained in the effect.
  72767. * @param camera The camera to get the post processes on.
  72768. * @returns The list of the post processes in the effect.
  72769. */
  72770. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72771. if (this._singleInstance) {
  72772. return this._postProcesses[0];
  72773. }
  72774. else {
  72775. if (!camera) {
  72776. return null;
  72777. }
  72778. return this._postProcesses[camera.name];
  72779. }
  72780. };
  72781. return PostProcessRenderEffect;
  72782. }());
  72783. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72784. })(BABYLON || (BABYLON = {}));
  72785. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72786. var BABYLON;
  72787. (function (BABYLON) {
  72788. var PostProcessRenderPipeline = /** @class */ (function () {
  72789. function PostProcessRenderPipeline(engine, name) {
  72790. this.engine = engine;
  72791. this._name = name;
  72792. this._renderEffects = {};
  72793. this._renderEffectsForIsolatedPass = new Array();
  72794. this._cameras = [];
  72795. }
  72796. PostProcessRenderPipeline.prototype.getClassName = function () {
  72797. return "PostProcessRenderPipeline";
  72798. };
  72799. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72800. get: function () {
  72801. for (var renderEffectName in this._renderEffects) {
  72802. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72803. if (!this._renderEffects[renderEffectName].isSupported) {
  72804. return false;
  72805. }
  72806. }
  72807. }
  72808. return true;
  72809. },
  72810. enumerable: true,
  72811. configurable: true
  72812. });
  72813. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72814. this._renderEffects[renderEffect._name] = renderEffect;
  72815. };
  72816. // private
  72817. PostProcessRenderPipeline.prototype._rebuild = function () {
  72818. };
  72819. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72820. var renderEffects = this._renderEffects[renderEffectName];
  72821. if (!renderEffects) {
  72822. return;
  72823. }
  72824. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72825. };
  72826. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72827. var renderEffects = this._renderEffects[renderEffectName];
  72828. if (!renderEffects) {
  72829. return;
  72830. }
  72831. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72832. };
  72833. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72834. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72835. if (!cams) {
  72836. return;
  72837. }
  72838. var indicesToDelete = [];
  72839. var i;
  72840. for (i = 0; i < cams.length; i++) {
  72841. var camera = cams[i];
  72842. var cameraName = camera.name;
  72843. if (this._cameras.indexOf(camera) === -1) {
  72844. this._cameras[cameraName] = camera;
  72845. }
  72846. else if (unique) {
  72847. indicesToDelete.push(i);
  72848. }
  72849. }
  72850. for (i = 0; i < indicesToDelete.length; i++) {
  72851. cameras.splice(indicesToDelete[i], 1);
  72852. }
  72853. for (var renderEffectName in this._renderEffects) {
  72854. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72855. this._renderEffects[renderEffectName]._attachCameras(cams);
  72856. }
  72857. }
  72858. };
  72859. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72860. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72861. if (!cams) {
  72862. return;
  72863. }
  72864. for (var renderEffectName in this._renderEffects) {
  72865. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72866. this._renderEffects[renderEffectName]._detachCameras(cams);
  72867. }
  72868. }
  72869. for (var i = 0; i < cams.length; i++) {
  72870. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72871. }
  72872. };
  72873. PostProcessRenderPipeline.prototype._update = function () {
  72874. for (var renderEffectName in this._renderEffects) {
  72875. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72876. this._renderEffects[renderEffectName]._update();
  72877. }
  72878. }
  72879. for (var i = 0; i < this._cameras.length; i++) {
  72880. var cameraName = this._cameras[i].name;
  72881. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72882. this._renderEffectsForIsolatedPass[cameraName]._update();
  72883. }
  72884. }
  72885. };
  72886. PostProcessRenderPipeline.prototype._reset = function () {
  72887. this._renderEffects = {};
  72888. this._renderEffectsForIsolatedPass = new Array();
  72889. };
  72890. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72891. // 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)
  72892. var effectKeys = Object.keys(this._renderEffects);
  72893. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72894. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72895. if (postProcesses) {
  72896. postProcesses[0].samples = sampleCount;
  72897. return true;
  72898. }
  72899. }
  72900. return false;
  72901. };
  72902. PostProcessRenderPipeline.prototype.dispose = function () {
  72903. // Must be implemented by children
  72904. };
  72905. __decorate([
  72906. BABYLON.serialize()
  72907. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72908. return PostProcessRenderPipeline;
  72909. }());
  72910. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72911. })(BABYLON || (BABYLON = {}));
  72912. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72913. var BABYLON;
  72914. (function (BABYLON) {
  72915. /**
  72916. * This represents a depth renderer in Babylon.
  72917. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72918. */
  72919. var DepthRenderer = /** @class */ (function () {
  72920. /**
  72921. * Instantiates a depth renderer
  72922. * @param scene The scene the renderer belongs to
  72923. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72924. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72925. */
  72926. function DepthRenderer(scene, type, camera) {
  72927. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72928. if (camera === void 0) { camera = null; }
  72929. var _this = this;
  72930. this._scene = scene;
  72931. this._camera = camera;
  72932. var engine = scene.getEngine();
  72933. // Render target
  72934. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72935. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72936. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72937. this._depthMap.refreshRate = 1;
  72938. this._depthMap.renderParticles = false;
  72939. this._depthMap.renderList = null;
  72940. // Camera to get depth map from to support multiple concurrent cameras
  72941. this._depthMap.activeCamera = this._camera;
  72942. this._depthMap.ignoreCameraViewport = true;
  72943. this._depthMap.useCameraPostProcesses = false;
  72944. // set default depth value to 1.0 (far away)
  72945. this._depthMap.onClearObservable.add(function (engine) {
  72946. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72947. });
  72948. // Custom render function
  72949. var renderSubMesh = function (subMesh) {
  72950. var mesh = subMesh.getRenderingMesh();
  72951. var scene = _this._scene;
  72952. var engine = scene.getEngine();
  72953. var material = subMesh.getMaterial();
  72954. if (!material) {
  72955. return;
  72956. }
  72957. // Culling and reverse (right handed system)
  72958. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72959. // Managing instances
  72960. var batch = mesh._getInstancesRenderList(subMesh._id);
  72961. if (batch.mustReturn) {
  72962. return;
  72963. }
  72964. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72965. var camera = _this._camera || scene.activeCamera;
  72966. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72967. engine.enableEffect(_this._effect);
  72968. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72969. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72970. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72971. // Alpha test
  72972. if (material && material.needAlphaTesting()) {
  72973. var alphaTexture = material.getAlphaTestTexture();
  72974. if (alphaTexture) {
  72975. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72976. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72977. }
  72978. }
  72979. // Bones
  72980. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72981. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72982. }
  72983. // Draw
  72984. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72985. }
  72986. };
  72987. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72988. var index;
  72989. if (depthOnlySubMeshes.length) {
  72990. engine.setColorWrite(false);
  72991. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72992. renderSubMesh(depthOnlySubMeshes.data[index]);
  72993. }
  72994. engine.setColorWrite(true);
  72995. }
  72996. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72997. renderSubMesh(opaqueSubMeshes.data[index]);
  72998. }
  72999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73000. renderSubMesh(alphaTestSubMeshes.data[index]);
  73001. }
  73002. };
  73003. }
  73004. /**
  73005. * Creates the depth rendering effect and checks if the effect is ready.
  73006. * @param subMesh The submesh to be used to render the depth map of
  73007. * @param useInstances If multiple world instances should be used
  73008. * @returns if the depth renderer is ready to render the depth map
  73009. */
  73010. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73011. var material = subMesh.getMaterial();
  73012. if (material.disableDepthWrite) {
  73013. return false;
  73014. }
  73015. var defines = [];
  73016. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73017. var mesh = subMesh.getMesh();
  73018. // Alpha test
  73019. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73020. defines.push("#define ALPHATEST");
  73021. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73022. attribs.push(BABYLON.VertexBuffer.UVKind);
  73023. defines.push("#define UV1");
  73024. }
  73025. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73026. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73027. defines.push("#define UV2");
  73028. }
  73029. }
  73030. // Bones
  73031. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73032. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73033. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73034. if (mesh.numBoneInfluencers > 4) {
  73035. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73036. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73037. }
  73038. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73039. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73040. }
  73041. else {
  73042. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73043. }
  73044. // Instances
  73045. if (useInstances) {
  73046. defines.push("#define INSTANCES");
  73047. attribs.push("world0");
  73048. attribs.push("world1");
  73049. attribs.push("world2");
  73050. attribs.push("world3");
  73051. }
  73052. // Get correct effect
  73053. var join = defines.join("\n");
  73054. if (this._cachedDefines !== join) {
  73055. this._cachedDefines = join;
  73056. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73057. }
  73058. return this._effect.isReady();
  73059. };
  73060. /**
  73061. * Gets the texture which the depth map will be written to.
  73062. * @returns The depth map texture
  73063. */
  73064. DepthRenderer.prototype.getDepthMap = function () {
  73065. return this._depthMap;
  73066. };
  73067. /**
  73068. * Disposes of the depth renderer.
  73069. */
  73070. DepthRenderer.prototype.dispose = function () {
  73071. this._depthMap.dispose();
  73072. };
  73073. return DepthRenderer;
  73074. }());
  73075. BABYLON.DepthRenderer = DepthRenderer;
  73076. })(BABYLON || (BABYLON = {}));
  73077. //# sourceMappingURL=babylon.depthRenderer.js.map
  73078. var BABYLON;
  73079. (function (BABYLON) {
  73080. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73081. __extends(SSAORenderingPipeline, _super);
  73082. /**
  73083. * @constructor
  73084. * @param {string} name - The rendering pipeline name
  73085. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73086. * @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 }
  73087. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73088. */
  73089. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73090. var _this = _super.call(this, scene.getEngine(), name) || this;
  73091. // Members
  73092. /**
  73093. * The PassPostProcess id in the pipeline that contains the original scene color
  73094. */
  73095. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73096. /**
  73097. * The SSAO PostProcess id in the pipeline
  73098. */
  73099. _this.SSAORenderEffect = "SSAORenderEffect";
  73100. /**
  73101. * The horizontal blur PostProcess id in the pipeline
  73102. */
  73103. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73104. /**
  73105. * The vertical blur PostProcess id in the pipeline
  73106. */
  73107. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73108. /**
  73109. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73110. */
  73111. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73112. /**
  73113. * The output strength of the SSAO post-process. Default value is 1.0.
  73114. */
  73115. _this.totalStrength = 1.0;
  73116. /**
  73117. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73118. */
  73119. _this.radius = 0.0001;
  73120. /**
  73121. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73122. * Must not be equal to fallOff and superior to fallOff.
  73123. * Default value is 0.975
  73124. */
  73125. _this.area = 0.0075;
  73126. /**
  73127. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73128. * Must not be equal to area and inferior to area.
  73129. * Default value is 0.0
  73130. */
  73131. _this.fallOff = 0.000001;
  73132. /**
  73133. * The base color of the SSAO post-process
  73134. * The final result is "base + ssao" between [0, 1]
  73135. */
  73136. _this.base = 0.5;
  73137. _this._firstUpdate = true;
  73138. _this._scene = scene;
  73139. // Set up assets
  73140. _this._createRandomTexture();
  73141. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73142. var ssaoRatio = ratio.ssaoRatio || ratio;
  73143. var combineRatio = ratio.combineRatio || ratio;
  73144. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73145. _this._createSSAOPostProcess(ssaoRatio);
  73146. _this._createBlurPostProcess(ssaoRatio);
  73147. _this._createSSAOCombinePostProcess(combineRatio);
  73148. // Set up pipeline
  73149. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73150. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73151. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73152. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73153. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73154. // Finish
  73155. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73156. if (cameras)
  73157. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73158. return _this;
  73159. }
  73160. // Public Methods
  73161. /**
  73162. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73163. */
  73164. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73165. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73166. for (var i = 0; i < this._scene.cameras.length; i++) {
  73167. var camera = this._scene.cameras[i];
  73168. this._originalColorPostProcess.dispose(camera);
  73169. this._ssaoPostProcess.dispose(camera);
  73170. this._blurHPostProcess.dispose(camera);
  73171. this._blurVPostProcess.dispose(camera);
  73172. this._ssaoCombinePostProcess.dispose(camera);
  73173. }
  73174. this._randomTexture.dispose();
  73175. if (disableDepthRender)
  73176. this._scene.disableDepthRenderer();
  73177. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73178. _super.prototype.dispose.call(this);
  73179. };
  73180. // Private Methods
  73181. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73182. var _this = this;
  73183. var size = 16;
  73184. 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);
  73185. 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);
  73186. this._blurHPostProcess.onActivateObservable.add(function () {
  73187. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73188. _this._blurHPostProcess.kernel = size * dw;
  73189. });
  73190. this._blurVPostProcess.onActivateObservable.add(function () {
  73191. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73192. _this._blurVPostProcess.kernel = size * dw;
  73193. });
  73194. };
  73195. SSAORenderingPipeline.prototype._rebuild = function () {
  73196. this._firstUpdate = true;
  73197. _super.prototype._rebuild.call(this);
  73198. };
  73199. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73200. var _this = this;
  73201. var numSamples = 16;
  73202. var sampleSphere = [
  73203. 0.5381, 0.1856, -0.4319,
  73204. 0.1379, 0.2486, 0.4430,
  73205. 0.3371, 0.5679, -0.0057,
  73206. -0.6999, -0.0451, -0.0019,
  73207. 0.0689, -0.1598, -0.8547,
  73208. 0.0560, 0.0069, -0.1843,
  73209. -0.0146, 0.1402, 0.0762,
  73210. 0.0100, -0.1924, -0.0344,
  73211. -0.3577, -0.5301, -0.4358,
  73212. -0.3169, 0.1063, 0.0158,
  73213. 0.0103, -0.5869, 0.0046,
  73214. -0.0897, -0.4940, 0.3287,
  73215. 0.7119, -0.0154, -0.0918,
  73216. -0.0533, 0.0596, -0.5411,
  73217. 0.0352, -0.0631, 0.5460,
  73218. -0.4776, 0.2847, -0.0271
  73219. ];
  73220. var samplesFactor = 1.0 / numSamples;
  73221. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73222. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73223. "area", "fallOff", "base", "range", "viewport"
  73224. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73225. this._ssaoPostProcess.onApply = function (effect) {
  73226. if (_this._firstUpdate) {
  73227. effect.setArray3("sampleSphere", sampleSphere);
  73228. effect.setFloat("samplesFactor", samplesFactor);
  73229. effect.setFloat("randTextureTiles", 4.0);
  73230. }
  73231. effect.setFloat("totalStrength", _this.totalStrength);
  73232. effect.setFloat("radius", _this.radius);
  73233. effect.setFloat("area", _this.area);
  73234. effect.setFloat("fallOff", _this.fallOff);
  73235. effect.setFloat("base", _this.base);
  73236. effect.setTexture("textureSampler", _this._depthTexture);
  73237. effect.setTexture("randomSampler", _this._randomTexture);
  73238. };
  73239. };
  73240. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73241. var _this = this;
  73242. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73243. this._ssaoCombinePostProcess.onApply = function (effect) {
  73244. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73245. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73246. };
  73247. };
  73248. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73249. var size = 512;
  73250. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73251. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73252. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73253. var context = this._randomTexture.getContext();
  73254. var rand = function (min, max) {
  73255. return Math.random() * (max - min) + min;
  73256. };
  73257. var randVector = BABYLON.Vector3.Zero();
  73258. for (var x = 0; x < size; x++) {
  73259. for (var y = 0; y < size; y++) {
  73260. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73261. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73262. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73263. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73264. context.fillRect(x, y, 1, 1);
  73265. }
  73266. }
  73267. this._randomTexture.update(false);
  73268. };
  73269. __decorate([
  73270. BABYLON.serialize()
  73271. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73272. __decorate([
  73273. BABYLON.serialize()
  73274. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73275. __decorate([
  73276. BABYLON.serialize()
  73277. ], SSAORenderingPipeline.prototype, "area", void 0);
  73278. __decorate([
  73279. BABYLON.serialize()
  73280. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73281. __decorate([
  73282. BABYLON.serialize()
  73283. ], SSAORenderingPipeline.prototype, "base", void 0);
  73284. return SSAORenderingPipeline;
  73285. }(BABYLON.PostProcessRenderPipeline));
  73286. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73287. })(BABYLON || (BABYLON = {}));
  73288. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73289. var BABYLON;
  73290. (function (BABYLON) {
  73291. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73292. __extends(SSAO2RenderingPipeline, _super);
  73293. /**
  73294. * @constructor
  73295. * @param {string} name - The rendering pipeline name
  73296. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73297. * @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 }
  73298. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73299. */
  73300. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73301. var _this = _super.call(this, scene.getEngine(), name) || this;
  73302. // Members
  73303. /**
  73304. * The PassPostProcess id in the pipeline that contains the original scene color
  73305. */
  73306. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73307. /**
  73308. * The SSAO PostProcess id in the pipeline
  73309. */
  73310. _this.SSAORenderEffect = "SSAORenderEffect";
  73311. /**
  73312. * The horizontal blur PostProcess id in the pipeline
  73313. */
  73314. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73315. /**
  73316. * The vertical blur PostProcess id in the pipeline
  73317. */
  73318. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73319. /**
  73320. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73321. */
  73322. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73323. /**
  73324. * The output strength of the SSAO post-process. Default value is 1.0.
  73325. */
  73326. _this.totalStrength = 1.0;
  73327. /**
  73328. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73329. */
  73330. _this.maxZ = 100.0;
  73331. /**
  73332. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73333. */
  73334. _this.minZAspect = 0.2;
  73335. /**
  73336. * Number of samples used for the SSAO calculations. Default value is 8
  73337. */
  73338. _this._samples = 8;
  73339. /**
  73340. * Are we using bilateral blur ?
  73341. */
  73342. _this._expensiveBlur = true;
  73343. /**
  73344. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73345. */
  73346. _this.radius = 2.0;
  73347. /**
  73348. * The base color of the SSAO post-process
  73349. * The final result is "base + ssao" between [0, 1]
  73350. */
  73351. _this.base = 0.1;
  73352. _this._firstUpdate = true;
  73353. _this._scene = scene;
  73354. _this._ratio = ratio;
  73355. if (!_this.isSupported) {
  73356. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73357. return _this;
  73358. }
  73359. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73360. var blurRatio = _this._ratio.blurRatio || ratio;
  73361. // Set up assets
  73362. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73363. _this._createRandomTexture();
  73364. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73365. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73366. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73367. _this._createSSAOPostProcess(1.0);
  73368. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73369. _this._createSSAOCombinePostProcess(blurRatio);
  73370. // Set up pipeline
  73371. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73372. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73373. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73374. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73375. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73376. // Finish
  73377. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73378. if (cameras)
  73379. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73380. return _this;
  73381. }
  73382. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73383. get: function () {
  73384. return this._samples;
  73385. },
  73386. set: function (n) {
  73387. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73388. this._samples = n;
  73389. this._sampleSphere = this._generateHemisphere();
  73390. this._firstUpdate = true;
  73391. },
  73392. enumerable: true,
  73393. configurable: true
  73394. });
  73395. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73396. get: function () {
  73397. return this._expensiveBlur;
  73398. },
  73399. set: function (b) {
  73400. 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"]);
  73401. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73402. this._expensiveBlur = b;
  73403. this._firstUpdate = true;
  73404. },
  73405. enumerable: true,
  73406. configurable: true
  73407. });
  73408. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73409. /**
  73410. * Support test.
  73411. */
  73412. get: function () {
  73413. var engine = BABYLON.Engine.LastCreatedEngine;
  73414. if (!engine) {
  73415. return false;
  73416. }
  73417. return engine.getCaps().drawBuffersExtension;
  73418. },
  73419. enumerable: true,
  73420. configurable: true
  73421. });
  73422. // Public Methods
  73423. /**
  73424. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73425. */
  73426. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73427. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73428. for (var i = 0; i < this._scene.cameras.length; i++) {
  73429. var camera = this._scene.cameras[i];
  73430. this._originalColorPostProcess.dispose(camera);
  73431. this._ssaoPostProcess.dispose(camera);
  73432. this._blurHPostProcess.dispose(camera);
  73433. this._blurVPostProcess.dispose(camera);
  73434. this._ssaoCombinePostProcess.dispose(camera);
  73435. }
  73436. this._randomTexture.dispose();
  73437. if (disableGeometryBufferRenderer)
  73438. this._scene.disableGeometryBufferRenderer();
  73439. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73440. _super.prototype.dispose.call(this);
  73441. };
  73442. // Private Methods
  73443. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73444. var _this = this;
  73445. this._samplerOffsets = [];
  73446. var expensive = this.expensiveBlur;
  73447. for (var i = -8; i < 8; i++) {
  73448. this._samplerOffsets.push(i * 2 + 0.5);
  73449. }
  73450. 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");
  73451. this._blurHPostProcess.onApply = function (effect) {
  73452. if (!_this._scene.activeCamera) {
  73453. return;
  73454. }
  73455. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73456. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73457. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73458. effect.setFloat("radius", _this.radius);
  73459. effect.setTexture("depthSampler", _this._depthTexture);
  73460. if (_this._firstUpdate) {
  73461. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73462. }
  73463. };
  73464. 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");
  73465. this._blurVPostProcess.onApply = function (effect) {
  73466. if (!_this._scene.activeCamera) {
  73467. return;
  73468. }
  73469. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73470. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73471. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73472. effect.setFloat("radius", _this.radius);
  73473. effect.setTexture("depthSampler", _this._depthTexture);
  73474. if (_this._firstUpdate) {
  73475. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73476. _this._firstUpdate = false;
  73477. }
  73478. };
  73479. };
  73480. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73481. this._firstUpdate = true;
  73482. _super.prototype._rebuild.call(this);
  73483. };
  73484. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73485. var numSamples = this.samples;
  73486. var result = [];
  73487. var vector, scale;
  73488. var rand = function (min, max) {
  73489. return Math.random() * (max - min) + min;
  73490. };
  73491. var i = 0;
  73492. while (i < numSamples) {
  73493. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73494. vector.normalize();
  73495. scale = i / numSamples;
  73496. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73497. vector.scaleInPlace(scale);
  73498. result.push(vector.x, vector.y, vector.z);
  73499. i++;
  73500. }
  73501. return result;
  73502. };
  73503. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73504. var _this = this;
  73505. var numSamples = this.samples;
  73506. this._sampleSphere = this._generateHemisphere();
  73507. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73508. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73509. "base", "range", "projection", "near", "far", "texelSize",
  73510. "xViewport", "yViewport", "maxZ", "minZAspect"
  73511. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73512. this._ssaoPostProcess.onApply = function (effect) {
  73513. if (_this._firstUpdate) {
  73514. effect.setArray3("sampleSphere", _this._sampleSphere);
  73515. effect.setFloat("randTextureTiles", 4.0);
  73516. }
  73517. if (!_this._scene.activeCamera) {
  73518. return;
  73519. }
  73520. effect.setFloat("samplesFactor", 1 / _this.samples);
  73521. effect.setFloat("totalStrength", _this.totalStrength);
  73522. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73523. effect.setFloat("radius", _this.radius);
  73524. effect.setFloat("maxZ", _this.maxZ);
  73525. effect.setFloat("minZAspect", _this.minZAspect);
  73526. effect.setFloat("base", _this.base);
  73527. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73528. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73529. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73530. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73531. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73532. effect.setTexture("textureSampler", _this._depthTexture);
  73533. effect.setTexture("normalSampler", _this._normalTexture);
  73534. effect.setTexture("randomSampler", _this._randomTexture);
  73535. };
  73536. };
  73537. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73538. var _this = this;
  73539. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73540. this._ssaoCombinePostProcess.onApply = function (effect) {
  73541. var viewport = _this._scene.activeCamera.viewport;
  73542. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73543. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73544. };
  73545. };
  73546. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73547. var size = 512;
  73548. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73549. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73550. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73551. var context = this._randomTexture.getContext();
  73552. var rand = function (min, max) {
  73553. return Math.random() * (max - min) + min;
  73554. };
  73555. var randVector = BABYLON.Vector3.Zero();
  73556. for (var x = 0; x < size; x++) {
  73557. for (var y = 0; y < size; y++) {
  73558. randVector.x = rand(0.0, 1.0);
  73559. randVector.y = rand(0.0, 1.0);
  73560. randVector.z = 0.0;
  73561. randVector.normalize();
  73562. randVector.scaleInPlace(255);
  73563. randVector.x = Math.floor(randVector.x);
  73564. randVector.y = Math.floor(randVector.y);
  73565. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73566. context.fillRect(x, y, 1, 1);
  73567. }
  73568. }
  73569. this._randomTexture.update(false);
  73570. };
  73571. /**
  73572. * Serialize the rendering pipeline (Used when exporting)
  73573. * @returns the serialized object
  73574. */
  73575. SSAO2RenderingPipeline.prototype.serialize = function () {
  73576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73577. serializationObject.customType = "SSAO2RenderingPipeline";
  73578. return serializationObject;
  73579. };
  73580. /**
  73581. * Parse the serialized pipeline
  73582. * @param source Source pipeline.
  73583. * @param scene The scene to load the pipeline to.
  73584. * @param rootUrl The URL of the serialized pipeline.
  73585. * @returns An instantiated pipeline from the serialized object.
  73586. */
  73587. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73588. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73589. };
  73590. __decorate([
  73591. BABYLON.serialize()
  73592. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73593. __decorate([
  73594. BABYLON.serialize()
  73595. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73596. __decorate([
  73597. BABYLON.serialize()
  73598. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73599. __decorate([
  73600. BABYLON.serialize("samples")
  73601. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73602. __decorate([
  73603. BABYLON.serialize()
  73604. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73605. __decorate([
  73606. BABYLON.serialize("expensiveBlur")
  73607. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73608. __decorate([
  73609. BABYLON.serialize()
  73610. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73611. __decorate([
  73612. BABYLON.serialize()
  73613. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73614. return SSAO2RenderingPipeline;
  73615. }(BABYLON.PostProcessRenderPipeline));
  73616. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73617. })(BABYLON || (BABYLON = {}));
  73618. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73619. // BABYLON.JS Chromatic Aberration GLSL Shader
  73620. // Author: Olivier Guyot
  73621. // Separates very slightly R, G and B colors on the edges of the screen
  73622. // Inspired by Francois Tarlier & Martins Upitis
  73623. var BABYLON;
  73624. (function (BABYLON) {
  73625. var LensRenderingPipeline = /** @class */ (function (_super) {
  73626. __extends(LensRenderingPipeline, _super);
  73627. /**
  73628. * @constructor
  73629. *
  73630. * Effect parameters are as follow:
  73631. * {
  73632. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73633. * edge_blur: number; // from 0 to x (1 for realism)
  73634. * distortion: number; // from 0 to x (1 for realism)
  73635. * grain_amount: number; // from 0 to 1
  73636. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73637. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73638. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73639. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73640. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73641. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73642. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73643. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73644. * }
  73645. * Note: if an effect parameter is unset, effect is disabled
  73646. *
  73647. * @param {string} name - The rendering pipeline name
  73648. * @param {object} parameters - An object containing all parameters (see above)
  73649. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73650. * @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)
  73651. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73652. */
  73653. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73654. if (ratio === void 0) { ratio = 1.0; }
  73655. var _this = _super.call(this, scene.getEngine(), name) || this;
  73656. // Lens effects can be of the following:
  73657. // - chromatic aberration (slight shift of RGB colors)
  73658. // - blur on the edge of the lens
  73659. // - lens distortion
  73660. // - depth-of-field blur & highlights enhancing
  73661. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73662. // - grain effect (noise or custom texture)
  73663. // Two additional texture samplers are needed:
  73664. // - depth map (for depth-of-field)
  73665. // - grain texture
  73666. /**
  73667. * The chromatic aberration PostProcess id in the pipeline
  73668. */
  73669. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73670. /**
  73671. * The highlights enhancing PostProcess id in the pipeline
  73672. */
  73673. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73674. /**
  73675. * The depth-of-field PostProcess id in the pipeline
  73676. */
  73677. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73678. _this._scene = scene;
  73679. // Fetch texture samplers
  73680. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73681. if (parameters.grain_texture) {
  73682. _this._grainTexture = parameters.grain_texture;
  73683. }
  73684. else {
  73685. _this._createGrainTexture();
  73686. }
  73687. // save parameters
  73688. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73689. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73690. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73691. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73692. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73693. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73694. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73695. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73696. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73697. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73698. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73699. // Create effects
  73700. _this._createChromaticAberrationPostProcess(ratio);
  73701. _this._createHighlightsPostProcess(ratio);
  73702. _this._createDepthOfFieldPostProcess(ratio / 4);
  73703. // Set up pipeline
  73704. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73705. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73706. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73707. if (_this._highlightsGain === -1) {
  73708. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73709. }
  73710. // Finish
  73711. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73712. if (cameras) {
  73713. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73714. }
  73715. return _this;
  73716. }
  73717. // public methods (self explanatory)
  73718. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73719. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73720. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73721. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73722. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73723. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73724. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73725. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73726. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73727. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73728. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73729. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73730. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73731. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73732. };
  73733. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73734. this._highlightsPostProcess.updateEffect();
  73735. };
  73736. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73737. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73738. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73739. this._highlightsGain = amount;
  73740. };
  73741. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73742. if (this._highlightsGain === -1) {
  73743. this._highlightsGain = 1.0;
  73744. }
  73745. this._highlightsThreshold = amount;
  73746. };
  73747. LensRenderingPipeline.prototype.disableHighlights = function () {
  73748. this._highlightsGain = -1;
  73749. };
  73750. /**
  73751. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73752. */
  73753. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73754. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73755. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73756. this._chromaticAberrationPostProcess = null;
  73757. this._highlightsPostProcess = null;
  73758. this._depthOfFieldPostProcess = null;
  73759. this._grainTexture.dispose();
  73760. if (disableDepthRender)
  73761. this._scene.disableDepthRenderer();
  73762. };
  73763. // colors shifting and distortion
  73764. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73765. var _this = this;
  73766. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73767. [], // samplers
  73768. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73769. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73770. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73771. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73772. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73773. effect.setFloat('radialIntensity', 1);
  73774. effect.setFloat2('direction', 17, 17);
  73775. effect.setFloat2('centerPosition', 0.5, 0.5);
  73776. };
  73777. };
  73778. // highlights enhancing
  73779. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73780. var _this = this;
  73781. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73782. [], // samplers
  73783. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73784. this._highlightsPostProcess.onApply = function (effect) {
  73785. effect.setFloat('gain', _this._highlightsGain);
  73786. effect.setFloat('threshold', _this._highlightsThreshold);
  73787. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73788. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73789. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73790. };
  73791. };
  73792. // colors shifting and distortion
  73793. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73794. var _this = this;
  73795. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73796. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73797. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73798. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73799. this._depthOfFieldPostProcess.onApply = function (effect) {
  73800. effect.setTexture("depthSampler", _this._depthTexture);
  73801. effect.setTexture("grainSampler", _this._grainTexture);
  73802. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73803. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73804. effect.setFloat('grain_amount', _this._grainAmount);
  73805. effect.setBool('blur_noise', _this._blurNoise);
  73806. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73807. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73808. effect.setFloat('distortion', _this._distortion);
  73809. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73810. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73811. effect.setFloat('aperture', _this._dofAperture);
  73812. effect.setFloat('darken', _this._dofDarken);
  73813. effect.setFloat('edge_blur', _this._edgeBlur);
  73814. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73815. if (_this._scene.activeCamera) {
  73816. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73817. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73818. }
  73819. };
  73820. };
  73821. // creates a black and white random noise texture, 512x512
  73822. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73823. var size = 512;
  73824. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73825. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73826. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73827. var context = this._grainTexture.getContext();
  73828. var rand = function (min, max) {
  73829. return Math.random() * (max - min) + min;
  73830. };
  73831. var value;
  73832. for (var x = 0; x < size; x++) {
  73833. for (var y = 0; y < size; y++) {
  73834. value = Math.floor(rand(0.42, 0.58) * 255);
  73835. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73836. context.fillRect(x, y, 1, 1);
  73837. }
  73838. }
  73839. this._grainTexture.update(false);
  73840. };
  73841. return LensRenderingPipeline;
  73842. }(BABYLON.PostProcessRenderPipeline));
  73843. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73844. })(BABYLON || (BABYLON = {}));
  73845. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73846. var BABYLON;
  73847. (function (BABYLON) {
  73848. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73849. __extends(StandardRenderingPipeline, _super);
  73850. /**
  73851. * @constructor
  73852. * @param {string} name - The rendering pipeline name
  73853. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73854. * @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)
  73855. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73856. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73857. */
  73858. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73859. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73860. var _this = _super.call(this, scene.getEngine(), name) || this;
  73861. _this.downSampleX4PostProcess = null;
  73862. _this.brightPassPostProcess = null;
  73863. _this.blurHPostProcesses = [];
  73864. _this.blurVPostProcesses = [];
  73865. _this.textureAdderPostProcess = null;
  73866. _this.volumetricLightPostProcess = null;
  73867. _this.volumetricLightSmoothXPostProcess = null;
  73868. _this.volumetricLightSmoothYPostProcess = null;
  73869. _this.volumetricLightMergePostProces = null;
  73870. _this.volumetricLightFinalPostProcess = null;
  73871. _this.luminancePostProcess = null;
  73872. _this.luminanceDownSamplePostProcesses = [];
  73873. _this.hdrPostProcess = null;
  73874. _this.textureAdderFinalPostProcess = null;
  73875. _this.lensFlareFinalPostProcess = null;
  73876. _this.hdrFinalPostProcess = null;
  73877. _this.lensFlarePostProcess = null;
  73878. _this.lensFlareComposePostProcess = null;
  73879. _this.motionBlurPostProcess = null;
  73880. _this.depthOfFieldPostProcess = null;
  73881. // Values
  73882. _this.brightThreshold = 1.0;
  73883. _this.blurWidth = 512.0;
  73884. _this.horizontalBlur = false;
  73885. _this.exposure = 1.0;
  73886. _this.lensTexture = null;
  73887. _this.volumetricLightCoefficient = 0.2;
  73888. _this.volumetricLightPower = 4.0;
  73889. _this.volumetricLightBlurScale = 64.0;
  73890. _this.sourceLight = null;
  73891. _this.hdrMinimumLuminance = 1.0;
  73892. _this.hdrDecreaseRate = 0.5;
  73893. _this.hdrIncreaseRate = 0.5;
  73894. _this.lensColorTexture = null;
  73895. _this.lensFlareStrength = 20.0;
  73896. _this.lensFlareGhostDispersal = 1.4;
  73897. _this.lensFlareHaloWidth = 0.7;
  73898. _this.lensFlareDistortionStrength = 16.0;
  73899. _this.lensStarTexture = null;
  73900. _this.lensFlareDirtTexture = null;
  73901. _this.depthOfFieldDistance = 10.0;
  73902. _this.depthOfFieldBlurWidth = 64.0;
  73903. _this.motionStrength = 1.0;
  73904. // IAnimatable
  73905. _this.animations = [];
  73906. _this._currentDepthOfFieldSource = null;
  73907. _this._hdrCurrentLuminance = 1.0;
  73908. // Getters and setters
  73909. _this._bloomEnabled = true;
  73910. _this._depthOfFieldEnabled = false;
  73911. _this._vlsEnabled = false;
  73912. _this._lensFlareEnabled = false;
  73913. _this._hdrEnabled = false;
  73914. _this._motionBlurEnabled = false;
  73915. _this._motionBlurSamples = 64.0;
  73916. _this._volumetricLightStepsCount = 50.0;
  73917. _this._cameras = cameras || [];
  73918. // Initialize
  73919. _this._scene = scene;
  73920. _this._basePostProcess = originalPostProcess;
  73921. _this._ratio = ratio;
  73922. // Misc
  73923. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73924. // Finish
  73925. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73926. _this._buildPipeline();
  73927. return _this;
  73928. }
  73929. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73930. get: function () {
  73931. return this._bloomEnabled;
  73932. },
  73933. set: function (enabled) {
  73934. if (this._bloomEnabled === enabled) {
  73935. return;
  73936. }
  73937. this._bloomEnabled = enabled;
  73938. this._buildPipeline();
  73939. },
  73940. enumerable: true,
  73941. configurable: true
  73942. });
  73943. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73944. get: function () {
  73945. return this._depthOfFieldEnabled;
  73946. },
  73947. set: function (enabled) {
  73948. if (this._depthOfFieldEnabled === enabled) {
  73949. return;
  73950. }
  73951. this._depthOfFieldEnabled = enabled;
  73952. this._buildPipeline();
  73953. },
  73954. enumerable: true,
  73955. configurable: true
  73956. });
  73957. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73958. get: function () {
  73959. return this._lensFlareEnabled;
  73960. },
  73961. set: function (enabled) {
  73962. if (this._lensFlareEnabled === enabled) {
  73963. return;
  73964. }
  73965. this._lensFlareEnabled = enabled;
  73966. this._buildPipeline();
  73967. },
  73968. enumerable: true,
  73969. configurable: true
  73970. });
  73971. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73972. get: function () {
  73973. return this._hdrEnabled;
  73974. },
  73975. set: function (enabled) {
  73976. if (this._hdrEnabled === enabled) {
  73977. return;
  73978. }
  73979. this._hdrEnabled = enabled;
  73980. this._buildPipeline();
  73981. },
  73982. enumerable: true,
  73983. configurable: true
  73984. });
  73985. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73986. get: function () {
  73987. return this._vlsEnabled;
  73988. },
  73989. set: function (enabled) {
  73990. if (this._vlsEnabled === enabled) {
  73991. return;
  73992. }
  73993. if (enabled) {
  73994. var geometry = this._scene.enableGeometryBufferRenderer();
  73995. if (!geometry) {
  73996. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73997. return;
  73998. }
  73999. }
  74000. this._vlsEnabled = enabled;
  74001. this._buildPipeline();
  74002. },
  74003. enumerable: true,
  74004. configurable: true
  74005. });
  74006. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74007. get: function () {
  74008. return this._motionBlurEnabled;
  74009. },
  74010. set: function (enabled) {
  74011. if (this._motionBlurEnabled === enabled) {
  74012. return;
  74013. }
  74014. this._motionBlurEnabled = enabled;
  74015. this._buildPipeline();
  74016. },
  74017. enumerable: true,
  74018. configurable: true
  74019. });
  74020. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74021. get: function () {
  74022. return this._volumetricLightStepsCount;
  74023. },
  74024. set: function (count) {
  74025. if (this.volumetricLightPostProcess) {
  74026. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74027. }
  74028. this._volumetricLightStepsCount = count;
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74034. get: function () {
  74035. return this._motionBlurSamples;
  74036. },
  74037. set: function (samples) {
  74038. if (this.motionBlurPostProcess) {
  74039. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74040. }
  74041. this._motionBlurSamples = samples;
  74042. },
  74043. enumerable: true,
  74044. configurable: true
  74045. });
  74046. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74047. var _this = this;
  74048. var ratio = this._ratio;
  74049. var scene = this._scene;
  74050. this._disposePostProcesses();
  74051. this._reset();
  74052. // Create pass post-process
  74053. if (!this._basePostProcess) {
  74054. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74055. this.originalPostProcess.onApply = function (effect) {
  74056. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74057. };
  74058. }
  74059. else {
  74060. this.originalPostProcess = this._basePostProcess;
  74061. }
  74062. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74063. this._currentDepthOfFieldSource = this.originalPostProcess;
  74064. if (this._bloomEnabled) {
  74065. // Create down sample X4 post-process
  74066. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74067. // Create bright pass post-process
  74068. this._createBrightPassPostProcess(scene, ratio / 2);
  74069. // Create gaussian blur post-processes (down sampling blurs)
  74070. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74071. // Create texture adder post-process
  74072. this._createTextureAdderPostProcess(scene, ratio);
  74073. // Create depth-of-field source post-process
  74074. 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);
  74075. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74076. }
  74077. if (this._vlsEnabled) {
  74078. // Create volumetric light
  74079. this._createVolumetricLightPostProcess(scene, ratio);
  74080. // Create volumetric light final post-process
  74081. 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);
  74082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74083. }
  74084. if (this._lensFlareEnabled) {
  74085. // Create lens flare post-process
  74086. this._createLensFlarePostProcess(scene, ratio);
  74087. // Create depth-of-field source post-process post lens-flare and disable it now
  74088. 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);
  74089. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74090. }
  74091. if (this._hdrEnabled) {
  74092. // Create luminance
  74093. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74094. // Create HDR
  74095. this._createHdrPostProcess(scene, ratio);
  74096. // Create depth-of-field source post-process post hdr and disable it now
  74097. 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);
  74098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74099. }
  74100. if (this._depthOfFieldEnabled) {
  74101. // Create gaussian blur used by depth-of-field
  74102. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74103. // Create depth-of-field post-process
  74104. this._createDepthOfFieldPostProcess(scene, ratio);
  74105. }
  74106. if (this._motionBlurEnabled) {
  74107. // Create motion blur post-process
  74108. this._createMotionBlurPostProcess(scene, ratio);
  74109. }
  74110. if (this._cameras !== null) {
  74111. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74112. }
  74113. };
  74114. // Down Sample X4 Post-Processs
  74115. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74116. var _this = this;
  74117. var downSampleX4Offsets = new Array(32);
  74118. 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);
  74119. this.downSampleX4PostProcess.onApply = function (effect) {
  74120. var id = 0;
  74121. var width = _this.downSampleX4PostProcess.width;
  74122. var height = _this.downSampleX4PostProcess.height;
  74123. for (var i = -2; i < 2; i++) {
  74124. for (var j = -2; j < 2; j++) {
  74125. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74126. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74127. id += 2;
  74128. }
  74129. }
  74130. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74131. };
  74132. // Add to pipeline
  74133. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74134. };
  74135. // Brightpass Post-Process
  74136. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74137. var _this = this;
  74138. var brightOffsets = new Array(8);
  74139. 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);
  74140. this.brightPassPostProcess.onApply = function (effect) {
  74141. var sU = (1.0 / _this.brightPassPostProcess.width);
  74142. var sV = (1.0 / _this.brightPassPostProcess.height);
  74143. brightOffsets[0] = -0.5 * sU;
  74144. brightOffsets[1] = 0.5 * sV;
  74145. brightOffsets[2] = 0.5 * sU;
  74146. brightOffsets[3] = 0.5 * sV;
  74147. brightOffsets[4] = -0.5 * sU;
  74148. brightOffsets[5] = -0.5 * sV;
  74149. brightOffsets[6] = 0.5 * sU;
  74150. brightOffsets[7] = -0.5 * sV;
  74151. effect.setArray2("dsOffsets", brightOffsets);
  74152. effect.setFloat("brightThreshold", _this.brightThreshold);
  74153. };
  74154. // Add to pipeline
  74155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74156. };
  74157. // Create blur H&V post-processes
  74158. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74159. var _this = this;
  74160. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74161. var engine = scene.getEngine();
  74162. 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);
  74163. 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);
  74164. blurX.onActivateObservable.add(function () {
  74165. var dw = blurX.width / engine.getRenderWidth();
  74166. blurX.kernel = _this[blurWidthKey] * dw;
  74167. });
  74168. blurY.onActivateObservable.add(function () {
  74169. var dw = blurY.height / engine.getRenderHeight();
  74170. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74171. });
  74172. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74174. this.blurHPostProcesses.push(blurX);
  74175. this.blurVPostProcesses.push(blurY);
  74176. };
  74177. // Create texture adder post-process
  74178. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74179. var _this = this;
  74180. 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);
  74181. this.textureAdderPostProcess.onApply = function (effect) {
  74182. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74183. effect.setTexture("lensSampler", _this.lensTexture);
  74184. effect.setFloat("exposure", _this.exposure);
  74185. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74186. };
  74187. // Add to pipeline
  74188. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74189. };
  74190. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74191. var _this = this;
  74192. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74193. geometryRenderer.enablePosition = true;
  74194. var geometry = geometryRenderer.getGBuffer();
  74195. // Base post-process
  74196. 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));
  74197. var depthValues = BABYLON.Vector2.Zero();
  74198. this.volumetricLightPostProcess.onApply = function (effect) {
  74199. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74200. var generator = _this.sourceLight.getShadowGenerator();
  74201. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74202. effect.setTexture("positionSampler", geometry.textures[2]);
  74203. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74204. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74205. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74206. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74207. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74208. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74209. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74210. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74211. effect.setVector2("depthValues", depthValues);
  74212. }
  74213. };
  74214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74215. // Smooth
  74216. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74217. // Merge
  74218. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74219. this.volumetricLightMergePostProces.onApply = function (effect) {
  74220. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74221. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74222. };
  74223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74224. };
  74225. // Create luminance
  74226. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74227. var _this = this;
  74228. // Create luminance
  74229. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74230. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74231. var offsets = [];
  74232. this.luminancePostProcess.onApply = function (effect) {
  74233. var sU = (1.0 / _this.luminancePostProcess.width);
  74234. var sV = (1.0 / _this.luminancePostProcess.height);
  74235. offsets[0] = -0.5 * sU;
  74236. offsets[1] = 0.5 * sV;
  74237. offsets[2] = 0.5 * sU;
  74238. offsets[3] = 0.5 * sV;
  74239. offsets[4] = -0.5 * sU;
  74240. offsets[5] = -0.5 * sV;
  74241. offsets[6] = 0.5 * sU;
  74242. offsets[7] = -0.5 * sV;
  74243. effect.setArray2("lumOffsets", offsets);
  74244. };
  74245. // Add to pipeline
  74246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74247. // Create down sample luminance
  74248. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74249. var size = Math.pow(3, i);
  74250. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74251. if (i === 0) {
  74252. defines += "#define FINAL_DOWN_SAMPLER";
  74253. }
  74254. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74255. this.luminanceDownSamplePostProcesses.push(postProcess);
  74256. }
  74257. // Create callbacks and add effects
  74258. var lastLuminance = this.luminancePostProcess;
  74259. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74260. var downSampleOffsets = new Array(18);
  74261. pp.onApply = function (effect) {
  74262. if (!lastLuminance) {
  74263. return;
  74264. }
  74265. var id = 0;
  74266. for (var x = -1; x < 2; x++) {
  74267. for (var y = -1; y < 2; y++) {
  74268. downSampleOffsets[id] = x / lastLuminance.width;
  74269. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74270. id += 2;
  74271. }
  74272. }
  74273. effect.setArray2("dsOffsets", downSampleOffsets);
  74274. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74275. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74276. lastLuminance = _this.luminancePostProcess;
  74277. }
  74278. else {
  74279. lastLuminance = pp;
  74280. }
  74281. };
  74282. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74283. pp.onAfterRender = function (effect) {
  74284. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74285. 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);
  74286. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74287. };
  74288. }
  74289. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74290. });
  74291. };
  74292. // Create HDR post-process
  74293. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74294. var _this = this;
  74295. 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);
  74296. var outputLiminance = 1;
  74297. var time = 0;
  74298. var lastTime = 0;
  74299. this.hdrPostProcess.onApply = function (effect) {
  74300. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74301. time += scene.getEngine().getDeltaTime();
  74302. if (outputLiminance < 0) {
  74303. outputLiminance = _this._hdrCurrentLuminance;
  74304. }
  74305. else {
  74306. var dt = (lastTime - time) / 1000.0;
  74307. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74308. outputLiminance += _this.hdrDecreaseRate * dt;
  74309. }
  74310. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74311. outputLiminance -= _this.hdrIncreaseRate * dt;
  74312. }
  74313. else {
  74314. outputLiminance = _this._hdrCurrentLuminance;
  74315. }
  74316. }
  74317. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74318. effect.setFloat("averageLuminance", outputLiminance);
  74319. lastTime = time;
  74320. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74321. };
  74322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74323. };
  74324. // Create lens flare post-process
  74325. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74326. var _this = this;
  74327. 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);
  74328. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74329. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74330. 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);
  74331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74332. var resolution = new BABYLON.Vector2(0, 0);
  74333. // Lens flare
  74334. this.lensFlarePostProcess.onApply = function (effect) {
  74335. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74336. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74337. effect.setFloat("strength", _this.lensFlareStrength);
  74338. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74339. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74340. // Shift
  74341. resolution.x = _this.lensFlarePostProcess.width;
  74342. resolution.y = _this.lensFlarePostProcess.height;
  74343. effect.setVector2("resolution", resolution);
  74344. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74345. };
  74346. // Compose
  74347. 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);
  74348. 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);
  74349. this.lensFlareComposePostProcess.onApply = function (effect) {
  74350. if (!_this._scene.activeCamera) {
  74351. return;
  74352. }
  74353. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74354. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74355. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74356. // Lens start rotation matrix
  74357. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74358. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74359. 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));
  74360. camRot *= 4.0;
  74361. 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);
  74362. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74363. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74364. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74365. };
  74366. };
  74367. // Create depth-of-field post-process
  74368. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74369. var _this = this;
  74370. 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);
  74371. this.depthOfFieldPostProcess.onApply = function (effect) {
  74372. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74373. effect.setTexture("depthSampler", _this._getDepthTexture());
  74374. effect.setFloat("distance", _this.depthOfFieldDistance);
  74375. };
  74376. // Add to pipeline
  74377. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74378. };
  74379. // Create motion blur post-process
  74380. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74381. var _this = this;
  74382. 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);
  74383. var motionScale = 0;
  74384. var prevViewProjection = BABYLON.Matrix.Identity();
  74385. var invViewProjection = BABYLON.Matrix.Identity();
  74386. var viewProjection = BABYLON.Matrix.Identity();
  74387. var screenSize = BABYLON.Vector2.Zero();
  74388. this.motionBlurPostProcess.onApply = function (effect) {
  74389. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74390. viewProjection.invertToRef(invViewProjection);
  74391. effect.setMatrix("inverseViewProjection", invViewProjection);
  74392. effect.setMatrix("prevViewProjection", prevViewProjection);
  74393. prevViewProjection = viewProjection;
  74394. screenSize.x = _this.motionBlurPostProcess.width;
  74395. screenSize.y = _this.motionBlurPostProcess.height;
  74396. effect.setVector2("screenSize", screenSize);
  74397. motionScale = scene.getEngine().getFps() / 60.0;
  74398. effect.setFloat("motionScale", motionScale);
  74399. effect.setFloat("motionStrength", _this.motionStrength);
  74400. effect.setTexture("depthSampler", _this._getDepthTexture());
  74401. };
  74402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74403. };
  74404. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74405. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74406. var renderer = this._scene.enableGeometryBufferRenderer();
  74407. return renderer.getGBuffer().textures[0];
  74408. }
  74409. return this._scene.enableDepthRenderer().getDepthMap();
  74410. };
  74411. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74412. for (var i = 0; i < this._cameras.length; i++) {
  74413. var camera = this._cameras[i];
  74414. if (this.originalPostProcess) {
  74415. this.originalPostProcess.dispose(camera);
  74416. }
  74417. if (this.downSampleX4PostProcess) {
  74418. this.downSampleX4PostProcess.dispose(camera);
  74419. }
  74420. if (this.brightPassPostProcess) {
  74421. this.brightPassPostProcess.dispose(camera);
  74422. }
  74423. if (this.textureAdderPostProcess) {
  74424. this.textureAdderPostProcess.dispose(camera);
  74425. }
  74426. if (this.textureAdderFinalPostProcess) {
  74427. this.textureAdderFinalPostProcess.dispose(camera);
  74428. }
  74429. if (this.volumetricLightPostProcess) {
  74430. this.volumetricLightPostProcess.dispose(camera);
  74431. }
  74432. if (this.volumetricLightSmoothXPostProcess) {
  74433. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74434. }
  74435. if (this.volumetricLightSmoothYPostProcess) {
  74436. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74437. }
  74438. if (this.volumetricLightMergePostProces) {
  74439. this.volumetricLightMergePostProces.dispose(camera);
  74440. }
  74441. if (this.volumetricLightFinalPostProcess) {
  74442. this.volumetricLightFinalPostProcess.dispose(camera);
  74443. }
  74444. if (this.lensFlarePostProcess) {
  74445. this.lensFlarePostProcess.dispose(camera);
  74446. }
  74447. if (this.lensFlareComposePostProcess) {
  74448. this.lensFlareComposePostProcess.dispose(camera);
  74449. }
  74450. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74451. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74452. }
  74453. if (this.luminancePostProcess) {
  74454. this.luminancePostProcess.dispose(camera);
  74455. }
  74456. if (this.hdrPostProcess) {
  74457. this.hdrPostProcess.dispose(camera);
  74458. }
  74459. if (this.hdrFinalPostProcess) {
  74460. this.hdrFinalPostProcess.dispose(camera);
  74461. }
  74462. if (this.depthOfFieldPostProcess) {
  74463. this.depthOfFieldPostProcess.dispose(camera);
  74464. }
  74465. if (this.motionBlurPostProcess) {
  74466. this.motionBlurPostProcess.dispose(camera);
  74467. }
  74468. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74469. this.blurHPostProcesses[j].dispose(camera);
  74470. }
  74471. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74472. this.blurVPostProcesses[j].dispose(camera);
  74473. }
  74474. }
  74475. this.originalPostProcess = null;
  74476. this.downSampleX4PostProcess = null;
  74477. this.brightPassPostProcess = null;
  74478. this.textureAdderPostProcess = null;
  74479. this.textureAdderFinalPostProcess = null;
  74480. this.volumetricLightPostProcess = null;
  74481. this.volumetricLightSmoothXPostProcess = null;
  74482. this.volumetricLightSmoothYPostProcess = null;
  74483. this.volumetricLightMergePostProces = null;
  74484. this.volumetricLightFinalPostProcess = null;
  74485. this.lensFlarePostProcess = null;
  74486. this.lensFlareComposePostProcess = null;
  74487. this.luminancePostProcess = null;
  74488. this.hdrPostProcess = null;
  74489. this.hdrFinalPostProcess = null;
  74490. this.depthOfFieldPostProcess = null;
  74491. this.motionBlurPostProcess = null;
  74492. this.luminanceDownSamplePostProcesses = [];
  74493. this.blurHPostProcesses = [];
  74494. this.blurVPostProcesses = [];
  74495. };
  74496. /**
  74497. * Dispose of the pipeline and stop all post processes
  74498. */
  74499. StandardRenderingPipeline.prototype.dispose = function () {
  74500. this._disposePostProcesses();
  74501. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74502. _super.prototype.dispose.call(this);
  74503. };
  74504. /**
  74505. * Serialize the rendering pipeline (Used when exporting)
  74506. * @returns the serialized object
  74507. */
  74508. StandardRenderingPipeline.prototype.serialize = function () {
  74509. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74510. if (this.sourceLight) {
  74511. serializationObject.sourceLightId = this.sourceLight.id;
  74512. }
  74513. serializationObject.customType = "StandardRenderingPipeline";
  74514. return serializationObject;
  74515. };
  74516. /**
  74517. * Parse the serialized pipeline
  74518. * @param source Source pipeline.
  74519. * @param scene The scene to load the pipeline to.
  74520. * @param rootUrl The URL of the serialized pipeline.
  74521. * @returns An instantiated pipeline from the serialized object.
  74522. */
  74523. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74524. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74525. if (source.sourceLightId) {
  74526. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74527. }
  74528. return p;
  74529. };
  74530. // Luminance steps
  74531. StandardRenderingPipeline.LuminanceSteps = 6;
  74532. __decorate([
  74533. BABYLON.serialize()
  74534. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74535. __decorate([
  74536. BABYLON.serialize()
  74537. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74538. __decorate([
  74539. BABYLON.serialize()
  74540. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74541. __decorate([
  74542. BABYLON.serialize()
  74543. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74544. __decorate([
  74545. BABYLON.serializeAsTexture("lensTexture")
  74546. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74547. __decorate([
  74548. BABYLON.serialize()
  74549. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74550. __decorate([
  74551. BABYLON.serialize()
  74552. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74553. __decorate([
  74554. BABYLON.serialize()
  74555. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74556. __decorate([
  74557. BABYLON.serialize()
  74558. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74559. __decorate([
  74560. BABYLON.serialize()
  74561. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74562. __decorate([
  74563. BABYLON.serialize()
  74564. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74565. __decorate([
  74566. BABYLON.serializeAsTexture("lensColorTexture")
  74567. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74568. __decorate([
  74569. BABYLON.serialize()
  74570. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74571. __decorate([
  74572. BABYLON.serialize()
  74573. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74574. __decorate([
  74575. BABYLON.serialize()
  74576. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74577. __decorate([
  74578. BABYLON.serialize()
  74579. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74580. __decorate([
  74581. BABYLON.serializeAsTexture("lensStarTexture")
  74582. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74583. __decorate([
  74584. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74585. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74586. __decorate([
  74587. BABYLON.serialize()
  74588. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74589. __decorate([
  74590. BABYLON.serialize()
  74591. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74592. __decorate([
  74593. BABYLON.serialize()
  74594. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74595. __decorate([
  74596. BABYLON.serialize()
  74597. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74598. __decorate([
  74599. BABYLON.serialize()
  74600. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74601. __decorate([
  74602. BABYLON.serialize()
  74603. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74604. __decorate([
  74605. BABYLON.serialize()
  74606. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74607. __decorate([
  74608. BABYLON.serialize()
  74609. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74610. __decorate([
  74611. BABYLON.serialize()
  74612. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74613. __decorate([
  74614. BABYLON.serialize()
  74615. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74616. __decorate([
  74617. BABYLON.serialize()
  74618. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74619. __decorate([
  74620. BABYLON.serialize()
  74621. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74622. return StandardRenderingPipeline;
  74623. }(BABYLON.PostProcessRenderPipeline));
  74624. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74625. })(BABYLON || (BABYLON = {}));
  74626. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74627. var BABYLON;
  74628. (function (BABYLON) {
  74629. var FxaaPostProcess = /** @class */ (function (_super) {
  74630. __extends(FxaaPostProcess, _super);
  74631. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74632. if (camera === void 0) { camera = null; }
  74633. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74634. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74635. var defines = _this._getDefines();
  74636. _this.updateEffect(defines);
  74637. _this.onApplyObservable.add(function (effect) {
  74638. var texelSize = _this.texelSize;
  74639. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74640. });
  74641. return _this;
  74642. }
  74643. FxaaPostProcess.prototype._getDefines = function () {
  74644. var engine = this.getEngine();
  74645. if (!engine) {
  74646. return null;
  74647. }
  74648. var glInfo = engine.getGlInfo();
  74649. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74650. return "#define MALI 1\n";
  74651. }
  74652. return null;
  74653. };
  74654. return FxaaPostProcess;
  74655. }(BABYLON.PostProcess));
  74656. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74657. })(BABYLON || (BABYLON = {}));
  74658. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74659. var BABYLON;
  74660. (function (BABYLON) {
  74661. /**
  74662. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74663. */
  74664. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74665. __extends(ChromaticAberrationPostProcess, _super);
  74666. /**
  74667. * Creates a new instance ChromaticAberrationPostProcess
  74668. * @param name The name of the effect.
  74669. * @param screenWidth The width of the screen to apply the effect on.
  74670. * @param screenHeight The height of the screen to apply the effect on.
  74671. * @param options The required width/height ratio to downsize to before computing the render pass.
  74672. * @param camera The camera to apply the render pass to.
  74673. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74674. * @param engine The engine which the post process will be applied. (default: current engine)
  74675. * @param reusable If the post process can be reused on the same frame. (default: false)
  74676. * @param textureType Type of textures used when performing the post process. (default: 0)
  74677. * @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)
  74678. */
  74679. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74680. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74681. if (blockCompilation === void 0) { blockCompilation = false; }
  74682. 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;
  74683. /**
  74684. * The amount of seperation of rgb channels (default: 30)
  74685. */
  74686. _this.aberrationAmount = 30;
  74687. /**
  74688. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74689. */
  74690. _this.radialIntensity = 0;
  74691. /**
  74692. * 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))
  74693. */
  74694. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74695. /**
  74696. * 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))
  74697. */
  74698. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74699. _this.onApplyObservable.add(function (effect) {
  74700. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74701. effect.setFloat('screen_width', screenWidth);
  74702. effect.setFloat('screen_height', screenHeight);
  74703. effect.setFloat('radialIntensity', _this.radialIntensity);
  74704. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74705. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74706. });
  74707. return _this;
  74708. }
  74709. return ChromaticAberrationPostProcess;
  74710. }(BABYLON.PostProcess));
  74711. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74712. })(BABYLON || (BABYLON = {}));
  74713. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74714. var BABYLON;
  74715. (function (BABYLON) {
  74716. /**
  74717. * The GrainPostProcess adds noise to the image at mid luminance levels
  74718. */
  74719. var GrainPostProcess = /** @class */ (function (_super) {
  74720. __extends(GrainPostProcess, _super);
  74721. /**
  74722. * Creates a new instance of @see GrainPostProcess
  74723. * @param name The name of the effect.
  74724. * @param options The required width/height ratio to downsize to before computing the render pass.
  74725. * @param camera The camera to apply the render pass to.
  74726. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74727. * @param engine The engine which the post process will be applied. (default: current engine)
  74728. * @param reusable If the post process can be reused on the same frame. (default: false)
  74729. * @param textureType Type of textures used when performing the post process. (default: 0)
  74730. * @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)
  74731. */
  74732. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74733. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74734. if (blockCompilation === void 0) { blockCompilation = false; }
  74735. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74736. /**
  74737. * The intensity of the grain added (default: 30)
  74738. */
  74739. _this.intensity = 30;
  74740. /**
  74741. * If the grain should be randomized on every frame
  74742. */
  74743. _this.animated = false;
  74744. _this.onApplyObservable.add(function (effect) {
  74745. effect.setFloat('intensity', _this.intensity);
  74746. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74747. });
  74748. return _this;
  74749. }
  74750. return GrainPostProcess;
  74751. }(BABYLON.PostProcess));
  74752. BABYLON.GrainPostProcess = GrainPostProcess;
  74753. })(BABYLON || (BABYLON = {}));
  74754. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74755. var BABYLON;
  74756. (function (BABYLON) {
  74757. /**
  74758. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74759. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74760. */
  74761. var SharpenPostProcess = /** @class */ (function (_super) {
  74762. __extends(SharpenPostProcess, _super);
  74763. /**
  74764. * Creates a new instance ConvolutionPostProcess
  74765. * @param name The name of the effect.
  74766. * @param options The required width/height ratio to downsize to before computing the render pass.
  74767. * @param camera The camera to apply the render pass to.
  74768. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74769. * @param engine The engine which the post process will be applied. (default: current engine)
  74770. * @param reusable If the post process can be reused on the same frame. (default: false)
  74771. * @param textureType Type of textures used when performing the post process. (default: 0)
  74772. * @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)
  74773. */
  74774. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74775. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74776. if (blockCompilation === void 0) { blockCompilation = false; }
  74777. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74778. /**
  74779. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74780. */
  74781. _this.colorAmount = 1.0;
  74782. /**
  74783. * How much sharpness should be applied (default: 0.3)
  74784. */
  74785. _this.edgeAmount = 0.3;
  74786. _this.onApply = function (effect) {
  74787. effect.setFloat2("screenSize", _this.width, _this.height);
  74788. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74789. };
  74790. return _this;
  74791. }
  74792. return SharpenPostProcess;
  74793. }(BABYLON.PostProcess));
  74794. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74795. })(BABYLON || (BABYLON = {}));
  74796. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74797. var BABYLON;
  74798. (function (BABYLON) {
  74799. /**
  74800. * The Blur Post Process which blurs an image based on a kernel and direction.
  74801. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74802. */
  74803. var BlurPostProcess = /** @class */ (function (_super) {
  74804. __extends(BlurPostProcess, _super);
  74805. /**
  74806. * Creates a new instance BlurPostProcess
  74807. * @param name The name of the effect.
  74808. * @param direction The direction in which to blur the image.
  74809. * @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.
  74810. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74811. * @param camera The camera to apply the render pass to.
  74812. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74813. * @param engine The engine which the post process will be applied. (default: current engine)
  74814. * @param reusable If the post process can be reused on the same frame. (default: false)
  74815. * @param textureType Type of textures used when performing the post process. (default: 0)
  74816. * @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)
  74817. */
  74818. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74819. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74820. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74821. if (defines === void 0) { defines = ""; }
  74822. if (blockCompilation === void 0) { blockCompilation = false; }
  74823. 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;
  74824. _this.direction = direction;
  74825. _this.blockCompilation = blockCompilation;
  74826. _this._packedFloat = false;
  74827. _this._staticDefines = "";
  74828. _this._staticDefines = defines;
  74829. _this.onApplyObservable.add(function (effect) {
  74830. if (_this._outputTexture) {
  74831. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74832. }
  74833. else {
  74834. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74835. }
  74836. });
  74837. _this.kernel = kernel;
  74838. return _this;
  74839. }
  74840. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74841. /**
  74842. * Gets the length in pixels of the blur sample region
  74843. */
  74844. get: function () {
  74845. return this._idealKernel;
  74846. },
  74847. /**
  74848. * Sets the length in pixels of the blur sample region
  74849. */
  74850. set: function (v) {
  74851. if (this._idealKernel === v) {
  74852. return;
  74853. }
  74854. v = Math.max(v, 1);
  74855. this._idealKernel = v;
  74856. this._kernel = this._nearestBestKernel(v);
  74857. if (!this.blockCompilation) {
  74858. this._updateParameters();
  74859. }
  74860. },
  74861. enumerable: true,
  74862. configurable: true
  74863. });
  74864. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74865. /**
  74866. * Gets wether or not the blur is unpacking/repacking floats
  74867. */
  74868. get: function () {
  74869. return this._packedFloat;
  74870. },
  74871. /**
  74872. * Sets wether or not the blur needs to unpack/repack floats
  74873. */
  74874. set: function (v) {
  74875. if (this._packedFloat === v) {
  74876. return;
  74877. }
  74878. this._packedFloat = v;
  74879. if (!this.blockCompilation) {
  74880. this._updateParameters();
  74881. }
  74882. },
  74883. enumerable: true,
  74884. configurable: true
  74885. });
  74886. /**
  74887. * Updates the effect with the current post process compile time values and recompiles the shader.
  74888. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74889. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74890. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74891. * @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
  74892. * @param onCompiled Called when the shader has been compiled.
  74893. * @param onError Called if there is an error when compiling a shader.
  74894. */
  74895. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74896. if (defines === void 0) { defines = null; }
  74897. if (uniforms === void 0) { uniforms = null; }
  74898. if (samplers === void 0) { samplers = null; }
  74899. this._updateParameters(onCompiled, onError);
  74900. };
  74901. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74902. // Generate sampling offsets and weights
  74903. var N = this._kernel;
  74904. var centerIndex = (N - 1) / 2;
  74905. // Generate Gaussian sampling weights over kernel
  74906. var offsets = [];
  74907. var weights = [];
  74908. var totalWeight = 0;
  74909. for (var i = 0; i < N; i++) {
  74910. var u = i / (N - 1);
  74911. var w = this._gaussianWeight(u * 2.0 - 1);
  74912. offsets[i] = (i - centerIndex);
  74913. weights[i] = w;
  74914. totalWeight += w;
  74915. }
  74916. // Normalize weights
  74917. for (var i = 0; i < weights.length; i++) {
  74918. weights[i] /= totalWeight;
  74919. }
  74920. // Optimize: combine samples to take advantage of hardware linear sampling
  74921. // Walk from left to center, combining pairs (symmetrically)
  74922. var linearSamplingWeights = [];
  74923. var linearSamplingOffsets = [];
  74924. var linearSamplingMap = [];
  74925. for (var i = 0; i <= centerIndex; i += 2) {
  74926. var j = Math.min(i + 1, Math.floor(centerIndex));
  74927. var singleCenterSample = i === j;
  74928. if (singleCenterSample) {
  74929. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74930. }
  74931. else {
  74932. var sharedCell = j === centerIndex;
  74933. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74934. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74935. if (offsetLinear === 0) {
  74936. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74937. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74938. }
  74939. else {
  74940. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74941. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74942. }
  74943. }
  74944. }
  74945. for (var i = 0; i < linearSamplingMap.length; i++) {
  74946. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74947. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74948. }
  74949. // Replace with optimized
  74950. offsets = linearSamplingOffsets;
  74951. weights = linearSamplingWeights;
  74952. // Generate shaders
  74953. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74954. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74955. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74956. var defines = "";
  74957. defines += this._staticDefines;
  74958. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74959. if (this._staticDefines.indexOf("DOF") != -1) {
  74960. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74961. varyingCount--;
  74962. }
  74963. for (var i = 0; i < varyingCount; i++) {
  74964. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74965. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74966. }
  74967. var depCount = 0;
  74968. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74969. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74970. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74971. depCount++;
  74972. }
  74973. if (this.packedFloat) {
  74974. defines += "#define PACKEDFLOAT 1";
  74975. }
  74976. this.blockCompilation = false;
  74977. _super.prototype.updateEffect.call(this, defines, null, null, {
  74978. varyingCount: varyingCount,
  74979. depCount: depCount
  74980. }, onCompiled, onError);
  74981. };
  74982. /**
  74983. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74984. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74985. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74986. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74987. * The gaps between physical kernels are compensated for in the weighting of the samples
  74988. * @param idealKernel Ideal blur kernel.
  74989. * @return Nearest best kernel.
  74990. */
  74991. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74992. var v = Math.round(idealKernel);
  74993. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74994. var k = _a[_i];
  74995. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74996. return Math.max(k, 3);
  74997. }
  74998. }
  74999. return Math.max(v, 3);
  75000. };
  75001. /**
  75002. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75003. * @param x The point on the Gaussian distribution to sample.
  75004. * @return the value of the Gaussian function at x.
  75005. */
  75006. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75007. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75008. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75009. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75010. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75011. // truncated at around 1.3% of peak strength.
  75012. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75013. var sigma = (1 / 3);
  75014. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75015. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75016. var weight = (1.0 / denominator) * Math.exp(exponent);
  75017. return weight;
  75018. };
  75019. /**
  75020. * Generates a string that can be used as a floating point number in GLSL.
  75021. * @param x Value to print.
  75022. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75023. * @return GLSL float string.
  75024. */
  75025. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75026. if (decimalFigures === void 0) { decimalFigures = 8; }
  75027. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75028. };
  75029. return BlurPostProcess;
  75030. }(BABYLON.PostProcess));
  75031. BABYLON.BlurPostProcess = BlurPostProcess;
  75032. })(BABYLON || (BABYLON = {}));
  75033. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75034. var BABYLON;
  75035. (function (BABYLON) {
  75036. /**
  75037. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75038. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75039. * based on samples that have a large difference in distance than the center pixel.
  75040. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75041. */
  75042. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75043. __extends(DepthOfFieldBlurPostProcess, _super);
  75044. /**
  75045. * Creates a new instance CircleOfConfusionPostProcess
  75046. * @param name The name of the effect.
  75047. * @param scene The scene the effect belongs to.
  75048. * @param direction The direction the blur should be applied.
  75049. * @param kernel The size of the kernel used to blur.
  75050. * @param options The required width/height ratio to downsize to before computing the render pass.
  75051. * @param camera The camera to apply the render pass to.
  75052. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75053. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75054. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75055. * @param engine The engine which the post process will be applied. (default: current engine)
  75056. * @param reusable If the post process can be reused on the same frame. (default: false)
  75057. * @param textureType Type of textures used when performing the post process. (default: 0)
  75058. * @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)
  75059. */
  75060. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75061. if (imageToBlur === void 0) { imageToBlur = null; }
  75062. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75063. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75064. if (blockCompilation === void 0) { blockCompilation = false; }
  75065. 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;
  75066. _this.direction = direction;
  75067. _this.onApplyObservable.add(function (effect) {
  75068. if (imageToBlur != null) {
  75069. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75070. }
  75071. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75072. if (scene.activeCamera) {
  75073. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75074. }
  75075. });
  75076. return _this;
  75077. }
  75078. return DepthOfFieldBlurPostProcess;
  75079. }(BABYLON.BlurPostProcess));
  75080. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75081. })(BABYLON || (BABYLON = {}));
  75082. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75083. var BABYLON;
  75084. (function (BABYLON) {
  75085. /**
  75086. * Options to be set when merging outputs from the default pipeline.
  75087. */
  75088. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75089. function DepthOfFieldMergePostProcessOptions() {
  75090. }
  75091. return DepthOfFieldMergePostProcessOptions;
  75092. }());
  75093. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75094. /**
  75095. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75096. */
  75097. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75098. __extends(DepthOfFieldMergePostProcess, _super);
  75099. /**
  75100. * Creates a new instance of DepthOfFieldMergePostProcess
  75101. * @param name The name of the effect.
  75102. * @param originalFromInput Post process which's input will be used for the merge.
  75103. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75104. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75105. * @param options The required width/height ratio to downsize to before computing the render pass.
  75106. * @param camera The camera to apply the render pass to.
  75107. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75108. * @param engine The engine which the post process will be applied. (default: current engine)
  75109. * @param reusable If the post process can be reused on the same frame. (default: false)
  75110. * @param textureType Type of textures used when performing the post process. (default: 0)
  75111. * @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)
  75112. */
  75113. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75114. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75115. if (blockCompilation === void 0) { blockCompilation = false; }
  75116. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75117. _this.blurSteps = blurSteps;
  75118. _this.onApplyObservable.add(function (effect) {
  75119. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75120. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75121. blurSteps.forEach(function (step, index) {
  75122. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75123. });
  75124. });
  75125. if (!blockCompilation) {
  75126. _this.updateEffect();
  75127. }
  75128. return _this;
  75129. }
  75130. /**
  75131. * Updates the effect with the current post process compile time values and recompiles the shader.
  75132. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75133. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75134. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75135. * @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
  75136. * @param onCompiled Called when the shader has been compiled.
  75137. * @param onError Called if there is an error when compiling a shader.
  75138. */
  75139. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75140. if (defines === void 0) { defines = null; }
  75141. if (uniforms === void 0) { uniforms = null; }
  75142. if (samplers === void 0) { samplers = null; }
  75143. if (!defines) {
  75144. defines = "";
  75145. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75146. }
  75147. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75148. };
  75149. return DepthOfFieldMergePostProcess;
  75150. }(BABYLON.PostProcess));
  75151. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75152. })(BABYLON || (BABYLON = {}));
  75153. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75154. var BABYLON;
  75155. (function (BABYLON) {
  75156. /**
  75157. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75158. */
  75159. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75160. __extends(CircleOfConfusionPostProcess, _super);
  75161. /**
  75162. * Creates a new instance CircleOfConfusionPostProcess
  75163. * @param name The name of the effect.
  75164. * @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.
  75165. * @param options The required width/height ratio to downsize to before computing the render pass.
  75166. * @param camera The camera to apply the render pass to.
  75167. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75168. * @param engine The engine which the post process will be applied. (default: current engine)
  75169. * @param reusable If the post process can be reused on the same frame. (default: false)
  75170. * @param textureType Type of textures used when performing the post process. (default: 0)
  75171. * @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)
  75172. */
  75173. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75174. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75175. if (blockCompilation === void 0) { blockCompilation = false; }
  75176. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75177. /**
  75178. * 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.
  75179. */
  75180. _this.lensSize = 50;
  75181. /**
  75182. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75183. */
  75184. _this.fStop = 1.4;
  75185. /**
  75186. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75187. */
  75188. _this.focusDistance = 2000;
  75189. /**
  75190. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75191. */
  75192. _this.focalLength = 50;
  75193. _this._depthTexture = null;
  75194. _this._depthTexture = depthTexture;
  75195. _this.onApplyObservable.add(function (effect) {
  75196. if (!_this._depthTexture) {
  75197. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75198. return;
  75199. }
  75200. effect.setTexture("depthSampler", _this._depthTexture);
  75201. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75202. var aperture = _this.lensSize / _this.fStop;
  75203. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75204. effect.setFloat('focusDistance', _this.focusDistance);
  75205. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75206. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75207. });
  75208. return _this;
  75209. }
  75210. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75211. /**
  75212. * 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.
  75213. */
  75214. set: function (value) {
  75215. this._depthTexture = value;
  75216. },
  75217. enumerable: true,
  75218. configurable: true
  75219. });
  75220. return CircleOfConfusionPostProcess;
  75221. }(BABYLON.PostProcess));
  75222. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75223. })(BABYLON || (BABYLON = {}));
  75224. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75225. var BABYLON;
  75226. (function (BABYLON) {
  75227. /**
  75228. * Specifies the level of max blur that should be applied when using the depth of field effect
  75229. */
  75230. var DepthOfFieldEffectBlurLevel;
  75231. (function (DepthOfFieldEffectBlurLevel) {
  75232. /**
  75233. * Subtle blur
  75234. */
  75235. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75236. /**
  75237. * Medium blur
  75238. */
  75239. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75240. /**
  75241. * Large blur
  75242. */
  75243. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75244. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75245. ;
  75246. /**
  75247. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75248. */
  75249. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75250. __extends(DepthOfFieldEffect, _super);
  75251. /**
  75252. * Creates a new instance DepthOfFieldEffect
  75253. * @param scene The scene the effect belongs to.
  75254. * @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.
  75255. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75256. * @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)
  75257. */
  75258. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75259. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75260. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75261. if (blockCompilation === void 0) { blockCompilation = false; }
  75262. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75263. return _this._effects;
  75264. }, true) || this;
  75265. /**
  75266. * Internal post processes in depth of field effect
  75267. */
  75268. _this._effects = [];
  75269. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75270. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75271. // 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)
  75272. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75273. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75274. _this._depthOfFieldBlurY = [];
  75275. _this._depthOfFieldBlurX = [];
  75276. var blurCount = 1;
  75277. var kernelSize = 15;
  75278. switch (blurLevel) {
  75279. case DepthOfFieldEffectBlurLevel.High: {
  75280. blurCount = 3;
  75281. kernelSize = 51;
  75282. break;
  75283. }
  75284. case DepthOfFieldEffectBlurLevel.Medium: {
  75285. blurCount = 2;
  75286. kernelSize = 31;
  75287. break;
  75288. }
  75289. default: {
  75290. kernelSize = 15;
  75291. blurCount = 1;
  75292. break;
  75293. }
  75294. }
  75295. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75296. var ratio = 1.0;
  75297. for (var i = 0; i < blurCount; i++) {
  75298. 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);
  75299. blurY.autoClear = false;
  75300. ratio = 0.75 / Math.pow(2, i);
  75301. 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);
  75302. blurX.autoClear = false;
  75303. _this._depthOfFieldBlurY.push(blurY);
  75304. _this._depthOfFieldBlurX.push(blurX);
  75305. }
  75306. // Set all post processes on the effect.
  75307. _this._effects = [_this._circleOfConfusion];
  75308. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75309. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75310. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75311. }
  75312. // Merge blurred images with original image based on circleOfConfusion
  75313. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75314. _this._dofMerge.autoClear = false;
  75315. _this._effects.push(_this._dofMerge);
  75316. return _this;
  75317. }
  75318. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75319. get: function () {
  75320. return this._circleOfConfusion.focalLength;
  75321. },
  75322. /**
  75323. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75324. */
  75325. set: function (value) {
  75326. this._circleOfConfusion.focalLength = value;
  75327. },
  75328. enumerable: true,
  75329. configurable: true
  75330. });
  75331. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75332. get: function () {
  75333. return this._circleOfConfusion.fStop;
  75334. },
  75335. /**
  75336. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75337. */
  75338. set: function (value) {
  75339. this._circleOfConfusion.fStop = value;
  75340. },
  75341. enumerable: true,
  75342. configurable: true
  75343. });
  75344. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75345. get: function () {
  75346. return this._circleOfConfusion.focusDistance;
  75347. },
  75348. /**
  75349. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75350. */
  75351. set: function (value) {
  75352. this._circleOfConfusion.focusDistance = value;
  75353. },
  75354. enumerable: true,
  75355. configurable: true
  75356. });
  75357. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75358. get: function () {
  75359. return this._circleOfConfusion.lensSize;
  75360. },
  75361. /**
  75362. * 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.
  75363. */
  75364. set: function (value) {
  75365. this._circleOfConfusion.lensSize = value;
  75366. },
  75367. enumerable: true,
  75368. configurable: true
  75369. });
  75370. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75371. /**
  75372. * 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.
  75373. */
  75374. set: function (value) {
  75375. this._circleOfConfusion.depthTexture = value;
  75376. },
  75377. enumerable: true,
  75378. configurable: true
  75379. });
  75380. /**
  75381. * Disposes each of the internal effects for a given camera.
  75382. * @param camera The camera to dispose the effect on.
  75383. */
  75384. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75385. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75386. this._effects[effectIndex].dispose(camera);
  75387. }
  75388. };
  75389. /**
  75390. * Internal
  75391. */
  75392. DepthOfFieldEffect.prototype._updateEffects = function () {
  75393. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75394. this._effects[effectIndex].updateEffect();
  75395. }
  75396. };
  75397. /**
  75398. * Internal
  75399. * @returns if all the contained post processes are ready.
  75400. */
  75401. DepthOfFieldEffect.prototype._isReady = function () {
  75402. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75403. if (!this._effects[effectIndex].isReady()) {
  75404. return false;
  75405. }
  75406. }
  75407. return true;
  75408. };
  75409. return DepthOfFieldEffect;
  75410. }(BABYLON.PostProcessRenderEffect));
  75411. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75412. })(BABYLON || (BABYLON = {}));
  75413. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75414. var BABYLON;
  75415. (function (BABYLON) {
  75416. /**
  75417. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75418. */
  75419. var BloomMergePostProcess = /** @class */ (function (_super) {
  75420. __extends(BloomMergePostProcess, _super);
  75421. /**
  75422. * Creates a new instance of @see BloomMergePostProcess
  75423. * @param name The name of the effect.
  75424. * @param originalFromInput Post process which's input will be used for the merge.
  75425. * @param blurred Blurred highlights post process which's output will be used.
  75426. * @param weight Weight of the bloom to be added to the original input.
  75427. * @param options The required width/height ratio to downsize to before computing the render pass.
  75428. * @param camera The camera to apply the render pass to.
  75429. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75430. * @param engine The engine which the post process will be applied. (default: current engine)
  75431. * @param reusable If the post process can be reused on the same frame. (default: false)
  75432. * @param textureType Type of textures used when performing the post process. (default: 0)
  75433. * @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)
  75434. */
  75435. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75436. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75437. if (blockCompilation === void 0) { blockCompilation = false; }
  75438. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75439. _this.weight = weight;
  75440. _this.onApplyObservable.add(function (effect) {
  75441. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75442. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75443. effect.setFloat("bloomWeight", _this.weight);
  75444. });
  75445. if (!blockCompilation) {
  75446. _this.updateEffect();
  75447. }
  75448. return _this;
  75449. }
  75450. return BloomMergePostProcess;
  75451. }(BABYLON.PostProcess));
  75452. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75453. })(BABYLON || (BABYLON = {}));
  75454. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75455. var BABYLON;
  75456. (function (BABYLON) {
  75457. /**
  75458. * 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.
  75459. */
  75460. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75461. __extends(ExtractHighlightsPostProcess, _super);
  75462. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75463. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75464. if (blockCompilation === void 0) { blockCompilation = false; }
  75465. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75466. /**
  75467. * The luminance threshold, pixels below this value will be set to black.
  75468. */
  75469. _this.threshold = 0.9;
  75470. /**
  75471. * Internal
  75472. */
  75473. _this._exposure = 1;
  75474. /**
  75475. * Post process which has the input texture to be used when performing highlight extraction
  75476. */
  75477. _this._inputPostProcess = null;
  75478. _this.onApplyObservable.add(function (effect) {
  75479. if (_this._inputPostProcess) {
  75480. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75481. }
  75482. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75483. effect.setFloat('exposure', _this._exposure);
  75484. });
  75485. return _this;
  75486. }
  75487. return ExtractHighlightsPostProcess;
  75488. }(BABYLON.PostProcess));
  75489. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75490. })(BABYLON || (BABYLON = {}));
  75491. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75492. var BABYLON;
  75493. (function (BABYLON) {
  75494. /**
  75495. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75496. */
  75497. var BloomEffect = /** @class */ (function (_super) {
  75498. __extends(BloomEffect, _super);
  75499. /**
  75500. * Creates a new instance of @see BloomEffect
  75501. * @param scene The scene the effect belongs to.
  75502. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75503. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75504. * @param bloomWeight The the strength of bloom.
  75505. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75506. * @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)
  75507. */
  75508. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75509. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75510. if (blockCompilation === void 0) { blockCompilation = false; }
  75511. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75512. return _this._effects;
  75513. }, true) || this;
  75514. _this.bloomScale = bloomScale;
  75515. /**
  75516. * Internal
  75517. */
  75518. _this._effects = [];
  75519. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75520. _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);
  75521. _this._blurX.alwaysForcePOT = true;
  75522. _this._blurX.autoClear = false;
  75523. _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);
  75524. _this._blurY.alwaysForcePOT = true;
  75525. _this._blurY.autoClear = false;
  75526. _this.kernel = bloomKernel;
  75527. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75528. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75529. _this._merge.autoClear = false;
  75530. _this._effects.push(_this._merge);
  75531. return _this;
  75532. }
  75533. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75534. /**
  75535. * The luminance threshold to find bright areas of the image to bloom.
  75536. */
  75537. get: function () {
  75538. return this._downscale.threshold;
  75539. },
  75540. set: function (value) {
  75541. this._downscale.threshold = value;
  75542. },
  75543. enumerable: true,
  75544. configurable: true
  75545. });
  75546. Object.defineProperty(BloomEffect.prototype, "weight", {
  75547. /**
  75548. * The strength of the bloom.
  75549. */
  75550. get: function () {
  75551. return this._merge.weight;
  75552. },
  75553. set: function (value) {
  75554. this._merge.weight = value;
  75555. },
  75556. enumerable: true,
  75557. configurable: true
  75558. });
  75559. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75560. /**
  75561. * Specifies the size of the bloom blur kernel, relative to the final output size
  75562. */
  75563. get: function () {
  75564. return this._blurX.kernel / this.bloomScale;
  75565. },
  75566. set: function (value) {
  75567. this._blurX.kernel = value * this.bloomScale;
  75568. this._blurY.kernel = value * this.bloomScale;
  75569. },
  75570. enumerable: true,
  75571. configurable: true
  75572. });
  75573. /**
  75574. * Disposes each of the internal effects for a given camera.
  75575. * @param camera The camera to dispose the effect on.
  75576. */
  75577. BloomEffect.prototype.disposeEffects = function (camera) {
  75578. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75579. this._effects[effectIndex].dispose(camera);
  75580. }
  75581. };
  75582. /**
  75583. * Internal
  75584. */
  75585. BloomEffect.prototype._updateEffects = function () {
  75586. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75587. this._effects[effectIndex].updateEffect();
  75588. }
  75589. };
  75590. /**
  75591. * Internal
  75592. * @returns if all the contained post processes are ready.
  75593. */
  75594. BloomEffect.prototype._isReady = function () {
  75595. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75596. if (!this._effects[effectIndex].isReady()) {
  75597. return false;
  75598. }
  75599. }
  75600. return true;
  75601. };
  75602. return BloomEffect;
  75603. }(BABYLON.PostProcessRenderEffect));
  75604. BABYLON.BloomEffect = BloomEffect;
  75605. })(BABYLON || (BABYLON = {}));
  75606. //# sourceMappingURL=babylon.bloomEffect.js.map
  75607. var BABYLON;
  75608. (function (BABYLON) {
  75609. /**
  75610. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75611. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75612. */
  75613. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75614. __extends(DefaultRenderingPipeline, _super);
  75615. /**
  75616. * @constructor
  75617. * @param {string} name - The rendering pipeline name (default: "")
  75618. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75619. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75620. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75621. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75622. */
  75623. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75624. if (name === void 0) { name = ""; }
  75625. if (hdr === void 0) { hdr = true; }
  75626. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75627. if (automaticBuild === void 0) { automaticBuild = true; }
  75628. var _this = _super.call(this, scene.getEngine(), name) || this;
  75629. _this._originalCameras = [];
  75630. /**
  75631. * ID of the sharpen post process,
  75632. */
  75633. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75634. /**
  75635. * ID of the image processing post process;
  75636. */
  75637. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75638. /**
  75639. * ID of the Fast Approximate Anti-Aliasing post process;
  75640. */
  75641. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75642. /**
  75643. * ID of the chromatic aberration post process,
  75644. */
  75645. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75646. /**
  75647. * ID of the grain post process
  75648. */
  75649. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75650. /**
  75651. * Glow post process which adds a glow to emmisive areas of the image
  75652. */
  75653. _this._glowLayer = null;
  75654. /**
  75655. * Animations which can be used to tweak settings over a period of time
  75656. */
  75657. _this.animations = [];
  75658. _this._imageProcessingConfigurationObserver = null;
  75659. // Values
  75660. _this._sharpenEnabled = false;
  75661. _this._bloomEnabled = false;
  75662. _this._depthOfFieldEnabled = false;
  75663. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75664. _this._fxaaEnabled = false;
  75665. _this._imageProcessingEnabled = true;
  75666. _this._bloomScale = 0.5;
  75667. _this._chromaticAberrationEnabled = false;
  75668. _this._grainEnabled = false;
  75669. _this._buildAllowed = true;
  75670. _this._resizeObserver = null;
  75671. _this._hardwareScaleLevel = 1.0;
  75672. _this._bloomKernel = 64;
  75673. /**
  75674. * Specifies the weight of the bloom in the final rendering
  75675. */
  75676. _this._bloomWeight = 0.15;
  75677. /**
  75678. * Specifies the luma threshold for the area that will be blurred by the bloom
  75679. */
  75680. _this._bloomThreshold = 0.9;
  75681. _this._samples = 1;
  75682. _this._hasCleared = false;
  75683. _this._prevPostProcess = null;
  75684. _this._prevPrevPostProcess = null;
  75685. _this._cameras = cameras || scene.cameras;
  75686. _this._originalCameras = _this._cameras.slice();
  75687. _this._buildAllowed = automaticBuild;
  75688. // Initialize
  75689. _this._scene = scene;
  75690. var caps = _this._scene.getEngine().getCaps();
  75691. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75692. // Misc
  75693. if (_this._hdr) {
  75694. if (caps.textureHalfFloatRender) {
  75695. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75696. }
  75697. else if (caps.textureFloatRender) {
  75698. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75699. }
  75700. }
  75701. else {
  75702. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75703. }
  75704. // Attach
  75705. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75706. var engine = _this._scene.getEngine();
  75707. // Create post processes before hand so they can be modified before enabled.
  75708. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75709. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75710. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75711. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75712. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75713. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75714. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75715. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75716. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75717. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75718. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75719. _this.bloomKernel = _this.bloomKernel;
  75720. });
  75721. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75722. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75723. });
  75724. _this._buildPipeline();
  75725. return _this;
  75726. }
  75727. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75728. get: function () {
  75729. return this._sharpenEnabled;
  75730. },
  75731. /**
  75732. * Enable or disable the sharpen process from the pipeline
  75733. */
  75734. set: function (enabled) {
  75735. if (this._sharpenEnabled === enabled) {
  75736. return;
  75737. }
  75738. this._sharpenEnabled = enabled;
  75739. this._buildPipeline();
  75740. },
  75741. enumerable: true,
  75742. configurable: true
  75743. });
  75744. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75745. /**
  75746. * Specifies the size of the bloom blur kernel, relative to the final output size
  75747. */
  75748. get: function () {
  75749. return this._bloomKernel;
  75750. },
  75751. set: function (value) {
  75752. this._bloomKernel = value;
  75753. this.bloom.kernel = value / this._hardwareScaleLevel;
  75754. },
  75755. enumerable: true,
  75756. configurable: true
  75757. });
  75758. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75759. get: function () {
  75760. return this._bloomWeight;
  75761. },
  75762. /**
  75763. * The strength of the bloom.
  75764. */
  75765. set: function (value) {
  75766. if (this._bloomWeight === value) {
  75767. return;
  75768. }
  75769. this.bloom.weight = value;
  75770. this._bloomWeight = value;
  75771. },
  75772. enumerable: true,
  75773. configurable: true
  75774. });
  75775. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75776. get: function () {
  75777. return this._bloomThreshold;
  75778. },
  75779. /**
  75780. * The strength of the bloom.
  75781. */
  75782. set: function (value) {
  75783. if (this._bloomThreshold === value) {
  75784. return;
  75785. }
  75786. this.bloom.threshold = value;
  75787. this._bloomThreshold = value;
  75788. },
  75789. enumerable: true,
  75790. configurable: true
  75791. });
  75792. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75793. get: function () {
  75794. return this._bloomScale;
  75795. },
  75796. /**
  75797. * The scale of the bloom, lower value will provide better performance.
  75798. */
  75799. set: function (value) {
  75800. if (this._bloomScale === value) {
  75801. return;
  75802. }
  75803. this._bloomScale = value;
  75804. // recreate bloom and dispose old as this setting is not dynamic
  75805. this._rebuildBloom();
  75806. this._buildPipeline();
  75807. },
  75808. enumerable: true,
  75809. configurable: true
  75810. });
  75811. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75812. get: function () {
  75813. return this._bloomEnabled;
  75814. },
  75815. /**
  75816. * Enable or disable the bloom from the pipeline
  75817. */
  75818. set: function (enabled) {
  75819. if (this._bloomEnabled === enabled) {
  75820. return;
  75821. }
  75822. this._bloomEnabled = enabled;
  75823. this._buildPipeline();
  75824. },
  75825. enumerable: true,
  75826. configurable: true
  75827. });
  75828. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75829. // recreate bloom and dispose old as this setting is not dynamic
  75830. var oldBloom = this.bloom;
  75831. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75832. this.bloom.threshold = oldBloom.threshold;
  75833. for (var i = 0; i < this._cameras.length; i++) {
  75834. oldBloom.disposeEffects(this._cameras[i]);
  75835. }
  75836. };
  75837. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75838. /**
  75839. * If the depth of field is enabled.
  75840. */
  75841. get: function () {
  75842. return this._depthOfFieldEnabled;
  75843. },
  75844. set: function (enabled) {
  75845. if (this._depthOfFieldEnabled === enabled) {
  75846. return;
  75847. }
  75848. this._depthOfFieldEnabled = enabled;
  75849. this._buildPipeline();
  75850. },
  75851. enumerable: true,
  75852. configurable: true
  75853. });
  75854. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75855. /**
  75856. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75857. */
  75858. get: function () {
  75859. return this._depthOfFieldBlurLevel;
  75860. },
  75861. set: function (value) {
  75862. if (this._depthOfFieldBlurLevel === value) {
  75863. return;
  75864. }
  75865. this._depthOfFieldBlurLevel = value;
  75866. // recreate dof and dispose old as this setting is not dynamic
  75867. var oldDof = this.depthOfField;
  75868. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75869. this.depthOfField.focalLength = oldDof.focalLength;
  75870. this.depthOfField.focusDistance = oldDof.focusDistance;
  75871. this.depthOfField.fStop = oldDof.fStop;
  75872. this.depthOfField.lensSize = oldDof.lensSize;
  75873. for (var i = 0; i < this._cameras.length; i++) {
  75874. oldDof.disposeEffects(this._cameras[i]);
  75875. }
  75876. this._buildPipeline();
  75877. },
  75878. enumerable: true,
  75879. configurable: true
  75880. });
  75881. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75882. get: function () {
  75883. return this._fxaaEnabled;
  75884. },
  75885. /**
  75886. * If the anti aliasing is enabled.
  75887. */
  75888. set: function (enabled) {
  75889. if (this._fxaaEnabled === enabled) {
  75890. return;
  75891. }
  75892. this._fxaaEnabled = enabled;
  75893. this._buildPipeline();
  75894. },
  75895. enumerable: true,
  75896. configurable: true
  75897. });
  75898. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75899. get: function () {
  75900. return this._samples;
  75901. },
  75902. /**
  75903. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75904. */
  75905. set: function (sampleCount) {
  75906. if (this._samples === sampleCount) {
  75907. return;
  75908. }
  75909. this._samples = sampleCount;
  75910. this._buildPipeline();
  75911. },
  75912. enumerable: true,
  75913. configurable: true
  75914. });
  75915. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75916. get: function () {
  75917. return this._imageProcessingEnabled;
  75918. },
  75919. /**
  75920. * If image processing is enabled.
  75921. */
  75922. set: function (enabled) {
  75923. if (this._imageProcessingEnabled === enabled) {
  75924. return;
  75925. }
  75926. this._imageProcessingEnabled = enabled;
  75927. this._buildPipeline();
  75928. },
  75929. enumerable: true,
  75930. configurable: true
  75931. });
  75932. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  75933. get: function () {
  75934. return this._glowLayer == null;
  75935. },
  75936. /**
  75937. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  75938. */
  75939. set: function (enabled) {
  75940. if (enabled && !this._glowLayer) {
  75941. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  75942. }
  75943. else if (!enabled && this._glowLayer) {
  75944. this._glowLayer.dispose();
  75945. this._glowLayer = null;
  75946. }
  75947. },
  75948. enumerable: true,
  75949. configurable: true
  75950. });
  75951. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75952. get: function () {
  75953. return this._chromaticAberrationEnabled;
  75954. },
  75955. /**
  75956. * Enable or disable the chromaticAberration process from the pipeline
  75957. */
  75958. set: function (enabled) {
  75959. if (this._chromaticAberrationEnabled === enabled) {
  75960. return;
  75961. }
  75962. this._chromaticAberrationEnabled = enabled;
  75963. this._buildPipeline();
  75964. },
  75965. enumerable: true,
  75966. configurable: true
  75967. });
  75968. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75969. get: function () {
  75970. return this._grainEnabled;
  75971. },
  75972. /**
  75973. * Enable or disable the grain process from the pipeline
  75974. */
  75975. set: function (enabled) {
  75976. if (this._grainEnabled === enabled) {
  75977. return;
  75978. }
  75979. this._grainEnabled = enabled;
  75980. this._buildPipeline();
  75981. },
  75982. enumerable: true,
  75983. configurable: true
  75984. });
  75985. /**
  75986. * Force the compilation of the entire pipeline.
  75987. */
  75988. DefaultRenderingPipeline.prototype.prepare = function () {
  75989. var previousState = this._buildAllowed;
  75990. this._buildAllowed = true;
  75991. this._buildPipeline();
  75992. this._buildAllowed = previousState;
  75993. };
  75994. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75995. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75996. if (this._hasCleared) {
  75997. postProcess.autoClear = false;
  75998. }
  75999. else {
  76000. postProcess.autoClear = true;
  76001. this._scene.autoClear = false;
  76002. this._hasCleared = true;
  76003. }
  76004. if (!skipTextureSharing) {
  76005. if (this._prevPrevPostProcess) {
  76006. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76007. }
  76008. else {
  76009. postProcess.useOwnOutput();
  76010. }
  76011. if (this._prevPostProcess) {
  76012. this._prevPrevPostProcess = this._prevPostProcess;
  76013. }
  76014. this._prevPostProcess = postProcess;
  76015. }
  76016. };
  76017. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76018. var _this = this;
  76019. if (!this._buildAllowed) {
  76020. return;
  76021. }
  76022. this._scene.autoClear = true;
  76023. var engine = this._scene.getEngine();
  76024. this._disposePostProcesses();
  76025. if (this._cameras !== null) {
  76026. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76027. // get back cameras to be used to reattach pipeline
  76028. this._cameras = this._originalCameras.slice();
  76029. }
  76030. this._reset();
  76031. this._prevPostProcess = null;
  76032. this._prevPrevPostProcess = null;
  76033. this._hasCleared = false;
  76034. if (this.depthOfFieldEnabled) {
  76035. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76036. this.depthOfField.depthTexture = depthTexture;
  76037. if (!this.depthOfField._isReady()) {
  76038. this.depthOfField._updateEffects();
  76039. }
  76040. this.addEffect(this.depthOfField);
  76041. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76042. }
  76043. if (this.bloomEnabled) {
  76044. if (!this.bloom._isReady()) {
  76045. this.bloom._updateEffects();
  76046. }
  76047. this.addEffect(this.bloom);
  76048. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76049. }
  76050. if (this._imageProcessingEnabled) {
  76051. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76052. if (this._hdr) {
  76053. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76054. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76055. }
  76056. else {
  76057. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76058. }
  76059. }
  76060. if (this.sharpenEnabled) {
  76061. if (!this.sharpen.isReady()) {
  76062. this.sharpen.updateEffect();
  76063. }
  76064. this.addEffect(this._sharpenEffect);
  76065. this._setAutoClearAndTextureSharing(this.sharpen);
  76066. }
  76067. if (this.grainEnabled) {
  76068. if (!this.grain.isReady()) {
  76069. this.grain.updateEffect();
  76070. }
  76071. this.addEffect(this._grainEffect);
  76072. this._setAutoClearAndTextureSharing(this.grain);
  76073. }
  76074. if (this.chromaticAberrationEnabled) {
  76075. if (!this.chromaticAberration.isReady()) {
  76076. this.chromaticAberration.updateEffect();
  76077. }
  76078. this.addEffect(this._chromaticAberrationEffect);
  76079. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76080. }
  76081. if (this.fxaaEnabled) {
  76082. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76083. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76084. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76085. }
  76086. if (this._cameras !== null) {
  76087. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76088. }
  76089. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76090. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76091. }
  76092. };
  76093. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76094. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76095. for (var i = 0; i < this._cameras.length; i++) {
  76096. var camera = this._cameras[i];
  76097. if (this.imageProcessing) {
  76098. this.imageProcessing.dispose(camera);
  76099. }
  76100. if (this.fxaa) {
  76101. this.fxaa.dispose(camera);
  76102. }
  76103. // These are created in the constructor and should not be disposed on every pipeline change
  76104. if (disposeNonRecreated) {
  76105. if (this.sharpen) {
  76106. this.sharpen.dispose(camera);
  76107. }
  76108. if (this.depthOfField) {
  76109. this.depthOfField.disposeEffects(camera);
  76110. }
  76111. if (this.bloom) {
  76112. this.bloom.disposeEffects(camera);
  76113. }
  76114. if (this.chromaticAberration) {
  76115. this.chromaticAberration.dispose(camera);
  76116. }
  76117. if (this.grain) {
  76118. this.grain.dispose(camera);
  76119. }
  76120. if (this._glowLayer) {
  76121. this._glowLayer.dispose();
  76122. }
  76123. }
  76124. }
  76125. this.imageProcessing = null;
  76126. this.fxaa = null;
  76127. if (disposeNonRecreated) {
  76128. this.sharpen = null;
  76129. this._sharpenEffect = null;
  76130. this.depthOfField = null;
  76131. this.bloom = null;
  76132. this.chromaticAberration = null;
  76133. this._chromaticAberrationEffect = null;
  76134. this.grain = null;
  76135. this._grainEffect = null;
  76136. this._glowLayer = null;
  76137. }
  76138. };
  76139. /**
  76140. * Dispose of the pipeline and stop all post processes
  76141. */
  76142. DefaultRenderingPipeline.prototype.dispose = function () {
  76143. this._disposePostProcesses(true);
  76144. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76145. this._scene.autoClear = true;
  76146. if (this._resizeObserver) {
  76147. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76148. this._resizeObserver = null;
  76149. }
  76150. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76151. _super.prototype.dispose.call(this);
  76152. };
  76153. /**
  76154. * Serialize the rendering pipeline (Used when exporting)
  76155. * @returns the serialized object
  76156. */
  76157. DefaultRenderingPipeline.prototype.serialize = function () {
  76158. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76159. serializationObject.customType = "DefaultRenderingPipeline";
  76160. return serializationObject;
  76161. };
  76162. /**
  76163. * Parse the serialized pipeline
  76164. * @param source Source pipeline.
  76165. * @param scene The scene to load the pipeline to.
  76166. * @param rootUrl The URL of the serialized pipeline.
  76167. * @returns An instantiated pipeline from the serialized object.
  76168. */
  76169. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76170. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76171. };
  76172. __decorate([
  76173. BABYLON.serialize()
  76174. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76175. __decorate([
  76176. BABYLON.serialize()
  76177. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76178. __decorate([
  76179. BABYLON.serialize()
  76180. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76181. __decorate([
  76182. BABYLON.serialize()
  76183. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76184. __decorate([
  76185. BABYLON.serialize()
  76186. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76187. __decorate([
  76188. BABYLON.serialize()
  76189. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76190. __decorate([
  76191. BABYLON.serialize()
  76192. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76193. __decorate([
  76194. BABYLON.serialize()
  76195. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76196. __decorate([
  76197. BABYLON.serialize()
  76198. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76199. __decorate([
  76200. BABYLON.serialize()
  76201. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76202. __decorate([
  76203. BABYLON.serialize()
  76204. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76205. __decorate([
  76206. BABYLON.serialize()
  76207. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76208. __decorate([
  76209. BABYLON.serialize()
  76210. ], DefaultRenderingPipeline.prototype, "samples", null);
  76211. __decorate([
  76212. BABYLON.serialize()
  76213. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76214. __decorate([
  76215. BABYLON.serialize()
  76216. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76217. __decorate([
  76218. BABYLON.serialize()
  76219. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76220. __decorate([
  76221. BABYLON.serialize()
  76222. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76223. return DefaultRenderingPipeline;
  76224. }(BABYLON.PostProcessRenderPipeline));
  76225. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76226. })(BABYLON || (BABYLON = {}));
  76227. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76228. var BABYLON;
  76229. (function (BABYLON) {
  76230. /**
  76231. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76232. */
  76233. var GeometryBufferRenderer = /** @class */ (function () {
  76234. /**
  76235. * Creates a new G Buffer for the scene
  76236. * @param scene The scene the buffer belongs to
  76237. * @param ratio How big is the buffer related to the main canvas.
  76238. */
  76239. function GeometryBufferRenderer(scene, ratio) {
  76240. if (ratio === void 0) { ratio = 1; }
  76241. this._enablePosition = false;
  76242. this._scene = scene;
  76243. this._ratio = ratio;
  76244. // Render target
  76245. this._createRenderTargets();
  76246. }
  76247. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76248. /**
  76249. * Set the render list (meshes to be rendered) used in the G buffer.
  76250. */
  76251. set: function (meshes) {
  76252. this._multiRenderTarget.renderList = meshes;
  76253. },
  76254. enumerable: true,
  76255. configurable: true
  76256. });
  76257. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76258. /**
  76259. * Gets wether or not G buffer are supported by the running hardware.
  76260. * This requires draw buffer supports
  76261. */
  76262. get: function () {
  76263. return this._multiRenderTarget.isSupported;
  76264. },
  76265. enumerable: true,
  76266. configurable: true
  76267. });
  76268. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76269. /**
  76270. * Gets wether or not position are enabled for the G buffer.
  76271. */
  76272. get: function () {
  76273. return this._enablePosition;
  76274. },
  76275. /**
  76276. * Sets wether or not position are enabled for the G buffer.
  76277. */
  76278. set: function (enable) {
  76279. this._enablePosition = enable;
  76280. this.dispose();
  76281. this._createRenderTargets();
  76282. },
  76283. enumerable: true,
  76284. configurable: true
  76285. });
  76286. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76287. /**
  76288. * Gets the scene associated with the buffer.
  76289. */
  76290. get: function () {
  76291. return this._scene;
  76292. },
  76293. enumerable: true,
  76294. configurable: true
  76295. });
  76296. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76297. /**
  76298. * Gets the ratio used by the buffer during its creation.
  76299. * How big is the buffer related to the main canvas.
  76300. */
  76301. get: function () {
  76302. return this._ratio;
  76303. },
  76304. enumerable: true,
  76305. configurable: true
  76306. });
  76307. /**
  76308. * Checks wether everything is ready to render a submesh to the G buffer.
  76309. * @param subMesh the submesh to check readiness for
  76310. * @param useInstances is the mesh drawn using instance or not
  76311. * @returns true if ready otherwise false
  76312. */
  76313. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76314. var material = subMesh.getMaterial();
  76315. if (material && material.disableDepthWrite) {
  76316. return false;
  76317. }
  76318. var defines = [];
  76319. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76320. var mesh = subMesh.getMesh();
  76321. // Alpha test
  76322. if (material && material.needAlphaTesting()) {
  76323. defines.push("#define ALPHATEST");
  76324. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76325. attribs.push(BABYLON.VertexBuffer.UVKind);
  76326. defines.push("#define UV1");
  76327. }
  76328. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76329. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76330. defines.push("#define UV2");
  76331. }
  76332. }
  76333. // Buffers
  76334. if (this._enablePosition) {
  76335. defines.push("#define POSITION");
  76336. }
  76337. // Bones
  76338. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76339. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76340. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76341. if (mesh.numBoneInfluencers > 4) {
  76342. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76343. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76344. }
  76345. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76346. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76347. }
  76348. else {
  76349. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76350. }
  76351. // Instances
  76352. if (useInstances) {
  76353. defines.push("#define INSTANCES");
  76354. attribs.push("world0");
  76355. attribs.push("world1");
  76356. attribs.push("world2");
  76357. attribs.push("world3");
  76358. }
  76359. // Get correct effect
  76360. var join = defines.join("\n");
  76361. if (this._cachedDefines !== join) {
  76362. this._cachedDefines = join;
  76363. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76364. }
  76365. return this._effect.isReady();
  76366. };
  76367. /**
  76368. * Gets the current underlying G Buffer.
  76369. * @returns the buffer
  76370. */
  76371. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76372. return this._multiRenderTarget;
  76373. };
  76374. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76375. /**
  76376. * Gets the number of samples used to render the buffer (anti aliasing).
  76377. */
  76378. get: function () {
  76379. return this._multiRenderTarget.samples;
  76380. },
  76381. /**
  76382. * Sets the number of samples used to render the buffer (anti aliasing).
  76383. */
  76384. set: function (value) {
  76385. this._multiRenderTarget.samples = value;
  76386. },
  76387. enumerable: true,
  76388. configurable: true
  76389. });
  76390. /**
  76391. * Disposes the renderer and frees up associated resources.
  76392. */
  76393. GeometryBufferRenderer.prototype.dispose = function () {
  76394. this.getGBuffer().dispose();
  76395. };
  76396. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76397. var _this = this;
  76398. var engine = this._scene.getEngine();
  76399. var count = this._enablePosition ? 3 : 2;
  76400. 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 });
  76401. if (!this.isSupported) {
  76402. return;
  76403. }
  76404. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76405. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76406. this._multiRenderTarget.refreshRate = 1;
  76407. this._multiRenderTarget.renderParticles = false;
  76408. this._multiRenderTarget.renderList = null;
  76409. // set default depth value to 1.0 (far away)
  76410. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76411. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76412. });
  76413. // Custom render function
  76414. var renderSubMesh = function (subMesh) {
  76415. var mesh = subMesh.getRenderingMesh();
  76416. var scene = _this._scene;
  76417. var engine = scene.getEngine();
  76418. var material = subMesh.getMaterial();
  76419. if (!material) {
  76420. return;
  76421. }
  76422. // Culling
  76423. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76424. // Managing instances
  76425. var batch = mesh._getInstancesRenderList(subMesh._id);
  76426. if (batch.mustReturn) {
  76427. return;
  76428. }
  76429. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76430. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76431. engine.enableEffect(_this._effect);
  76432. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76433. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76434. _this._effect.setMatrix("view", scene.getViewMatrix());
  76435. // Alpha test
  76436. if (material && material.needAlphaTesting()) {
  76437. var alphaTexture = material.getAlphaTestTexture();
  76438. if (alphaTexture) {
  76439. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76440. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76441. }
  76442. }
  76443. // Bones
  76444. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76445. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76446. }
  76447. // Draw
  76448. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76449. }
  76450. };
  76451. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76452. var index;
  76453. if (depthOnlySubMeshes.length) {
  76454. engine.setColorWrite(false);
  76455. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76456. renderSubMesh(depthOnlySubMeshes.data[index]);
  76457. }
  76458. engine.setColorWrite(true);
  76459. }
  76460. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76461. renderSubMesh(opaqueSubMeshes.data[index]);
  76462. }
  76463. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76464. renderSubMesh(alphaTestSubMeshes.data[index]);
  76465. }
  76466. };
  76467. };
  76468. return GeometryBufferRenderer;
  76469. }());
  76470. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76471. })(BABYLON || (BABYLON = {}));
  76472. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76473. var BABYLON;
  76474. (function (BABYLON) {
  76475. var RefractionPostProcess = /** @class */ (function (_super) {
  76476. __extends(RefractionPostProcess, _super);
  76477. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76478. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76479. _this.color = color;
  76480. _this.depth = depth;
  76481. _this.colorLevel = colorLevel;
  76482. _this._ownRefractionTexture = true;
  76483. _this.onActivateObservable.add(function (cam) {
  76484. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76485. });
  76486. _this.onApplyObservable.add(function (effect) {
  76487. effect.setColor3("baseColor", _this.color);
  76488. effect.setFloat("depth", _this.depth);
  76489. effect.setFloat("colorLevel", _this.colorLevel);
  76490. effect.setTexture("refractionSampler", _this._refTexture);
  76491. });
  76492. return _this;
  76493. }
  76494. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76495. /**
  76496. * Gets or sets the refraction texture
  76497. * Please note that you are responsible for disposing the texture if you set it manually
  76498. */
  76499. get: function () {
  76500. return this._refTexture;
  76501. },
  76502. set: function (value) {
  76503. if (this._refTexture && this._ownRefractionTexture) {
  76504. this._refTexture.dispose();
  76505. }
  76506. this._refTexture = value;
  76507. this._ownRefractionTexture = false;
  76508. },
  76509. enumerable: true,
  76510. configurable: true
  76511. });
  76512. // Methods
  76513. RefractionPostProcess.prototype.dispose = function (camera) {
  76514. if (this._refTexture && this._ownRefractionTexture) {
  76515. this._refTexture.dispose();
  76516. this._refTexture = null;
  76517. }
  76518. _super.prototype.dispose.call(this, camera);
  76519. };
  76520. return RefractionPostProcess;
  76521. }(BABYLON.PostProcess));
  76522. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76523. })(BABYLON || (BABYLON = {}));
  76524. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76525. var BABYLON;
  76526. (function (BABYLON) {
  76527. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76528. __extends(BlackAndWhitePostProcess, _super);
  76529. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76530. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76531. _this.degree = 1;
  76532. _this.onApplyObservable.add(function (effect) {
  76533. effect.setFloat("degree", _this.degree);
  76534. });
  76535. return _this;
  76536. }
  76537. return BlackAndWhitePostProcess;
  76538. }(BABYLON.PostProcess));
  76539. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76540. })(BABYLON || (BABYLON = {}));
  76541. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76542. var BABYLON;
  76543. (function (BABYLON) {
  76544. /**
  76545. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76546. * input texture to perform effects such as edge detection or sharpening
  76547. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76548. */
  76549. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76550. __extends(ConvolutionPostProcess, _super);
  76551. /**
  76552. * Creates a new instance ConvolutionPostProcess
  76553. * @param name The name of the effect.
  76554. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76555. * @param options The required width/height ratio to downsize to before computing the render pass.
  76556. * @param camera The camera to apply the render pass to.
  76557. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76558. * @param engine The engine which the post process will be applied. (default: current engine)
  76559. * @param reusable If the post process can be reused on the same frame. (default: false)
  76560. * @param textureType Type of textures used when performing the post process. (default: 0)
  76561. */
  76562. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76563. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76564. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76565. _this.kernel = kernel;
  76566. _this.onApply = function (effect) {
  76567. effect.setFloat2("screenSize", _this.width, _this.height);
  76568. effect.setArray("kernel", _this.kernel);
  76569. };
  76570. return _this;
  76571. }
  76572. // Statics
  76573. /**
  76574. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76575. */
  76576. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76577. /**
  76578. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76579. */
  76580. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76581. /**
  76582. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76583. */
  76584. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76585. /**
  76586. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76587. */
  76588. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76589. /**
  76590. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76591. */
  76592. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76593. /**
  76594. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76595. */
  76596. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76597. return ConvolutionPostProcess;
  76598. }(BABYLON.PostProcess));
  76599. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76600. })(BABYLON || (BABYLON = {}));
  76601. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76602. var BABYLON;
  76603. (function (BABYLON) {
  76604. var FilterPostProcess = /** @class */ (function (_super) {
  76605. __extends(FilterPostProcess, _super);
  76606. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76607. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76608. _this.kernelMatrix = kernelMatrix;
  76609. _this.onApply = function (effect) {
  76610. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76611. };
  76612. return _this;
  76613. }
  76614. return FilterPostProcess;
  76615. }(BABYLON.PostProcess));
  76616. BABYLON.FilterPostProcess = FilterPostProcess;
  76617. })(BABYLON || (BABYLON = {}));
  76618. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76619. var BABYLON;
  76620. (function (BABYLON) {
  76621. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76622. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76623. __extends(VolumetricLightScatteringPostProcess, _super);
  76624. /**
  76625. * @constructor
  76626. * @param {string} name - The post-process name
  76627. * @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)
  76628. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76629. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76630. * @param {number} samples - The post-process quality, default 100
  76631. * @param {number} samplingMode - The post-process filtering mode
  76632. * @param {BABYLON.Engine} engine - The babylon engine
  76633. * @param {boolean} reusable - If the post-process is reusable
  76634. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76635. */
  76636. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76637. if (samples === void 0) { samples = 100; }
  76638. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76639. 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;
  76640. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76641. /**
  76642. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76643. */
  76644. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76645. /**
  76646. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76647. */
  76648. _this.useCustomMeshPosition = false;
  76649. /**
  76650. * If the post-process should inverse the light scattering direction
  76651. */
  76652. _this.invert = true;
  76653. /**
  76654. * Array containing the excluded meshes not rendered in the internal pass
  76655. */
  76656. _this.excludedMeshes = new Array();
  76657. /**
  76658. * Controls the overall intensity of the post-process
  76659. */
  76660. _this.exposure = 0.3;
  76661. /**
  76662. * Dissipates each sample's contribution in range [0, 1]
  76663. */
  76664. _this.decay = 0.96815;
  76665. /**
  76666. * Controls the overall intensity of each sample
  76667. */
  76668. _this.weight = 0.58767;
  76669. /**
  76670. * Controls the density of each sample
  76671. */
  76672. _this.density = 0.926;
  76673. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76674. engine = scene.getEngine();
  76675. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76676. // Configure mesh
  76677. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76678. // Configure
  76679. _this._createPass(scene, ratio.passRatio || ratio);
  76680. _this.onActivate = function (camera) {
  76681. if (!_this.isSupported) {
  76682. _this.dispose(camera);
  76683. }
  76684. _this.onActivate = null;
  76685. };
  76686. _this.onApplyObservable.add(function (effect) {
  76687. _this._updateMeshScreenCoordinates(scene);
  76688. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76689. effect.setFloat("exposure", _this.exposure);
  76690. effect.setFloat("decay", _this.decay);
  76691. effect.setFloat("weight", _this.weight);
  76692. effect.setFloat("density", _this.density);
  76693. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76694. });
  76695. return _this;
  76696. }
  76697. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76698. get: function () {
  76699. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76700. return false;
  76701. },
  76702. set: function (useDiffuseColor) {
  76703. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76704. },
  76705. enumerable: true,
  76706. configurable: true
  76707. });
  76708. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76709. return "VolumetricLightScatteringPostProcess";
  76710. };
  76711. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76712. var mesh = subMesh.getMesh();
  76713. // Render this.mesh as default
  76714. if (mesh === this.mesh && mesh.material) {
  76715. return mesh.material.isReady(mesh);
  76716. }
  76717. var defines = [];
  76718. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76719. var material = subMesh.getMaterial();
  76720. // Alpha test
  76721. if (material) {
  76722. if (material.needAlphaTesting()) {
  76723. defines.push("#define ALPHATEST");
  76724. }
  76725. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76726. attribs.push(BABYLON.VertexBuffer.UVKind);
  76727. defines.push("#define UV1");
  76728. }
  76729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76730. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76731. defines.push("#define UV2");
  76732. }
  76733. }
  76734. // Bones
  76735. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76738. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76739. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76740. }
  76741. else {
  76742. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76743. }
  76744. // Instances
  76745. if (useInstances) {
  76746. defines.push("#define INSTANCES");
  76747. attribs.push("world0");
  76748. attribs.push("world1");
  76749. attribs.push("world2");
  76750. attribs.push("world3");
  76751. }
  76752. // Get correct effect
  76753. var join = defines.join("\n");
  76754. if (this._cachedDefines !== join) {
  76755. this._cachedDefines = join;
  76756. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76757. }
  76758. return this._volumetricLightScatteringPass.isReady();
  76759. };
  76760. /**
  76761. * Sets the new light position for light scattering effect
  76762. * @param {BABYLON.Vector3} The new custom light position
  76763. */
  76764. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76765. this.customMeshPosition = position;
  76766. };
  76767. /**
  76768. * Returns the light position for light scattering effect
  76769. * @return {BABYLON.Vector3} The custom light position
  76770. */
  76771. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76772. return this.customMeshPosition;
  76773. };
  76774. /**
  76775. * Disposes the internal assets and detaches the post-process from the camera
  76776. */
  76777. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76778. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76779. if (rttIndex !== -1) {
  76780. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76781. }
  76782. this._volumetricLightScatteringRTT.dispose();
  76783. _super.prototype.dispose.call(this, camera);
  76784. };
  76785. /**
  76786. * Returns the render target texture used by the post-process
  76787. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76788. */
  76789. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76790. return this._volumetricLightScatteringRTT;
  76791. };
  76792. // Private methods
  76793. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76794. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76795. return true;
  76796. }
  76797. return false;
  76798. };
  76799. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76800. var _this = this;
  76801. var engine = scene.getEngine();
  76802. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76803. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76804. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76805. this._volumetricLightScatteringRTT.renderList = null;
  76806. this._volumetricLightScatteringRTT.renderParticles = false;
  76807. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76808. var camera = this.getCamera();
  76809. if (camera) {
  76810. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76811. }
  76812. else {
  76813. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76814. }
  76815. // Custom render function for submeshes
  76816. var renderSubMesh = function (subMesh) {
  76817. var mesh = subMesh.getRenderingMesh();
  76818. if (_this._meshExcluded(mesh)) {
  76819. return;
  76820. }
  76821. var material = subMesh.getMaterial();
  76822. if (!material) {
  76823. return;
  76824. }
  76825. var scene = mesh.getScene();
  76826. var engine = scene.getEngine();
  76827. // Culling
  76828. engine.setState(material.backFaceCulling);
  76829. // Managing instances
  76830. var batch = mesh._getInstancesRenderList(subMesh._id);
  76831. if (batch.mustReturn) {
  76832. return;
  76833. }
  76834. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76835. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76836. var effect = _this._volumetricLightScatteringPass;
  76837. if (mesh === _this.mesh) {
  76838. if (subMesh.effect) {
  76839. effect = subMesh.effect;
  76840. }
  76841. else {
  76842. effect = material.getEffect();
  76843. }
  76844. }
  76845. engine.enableEffect(effect);
  76846. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76847. if (mesh === _this.mesh) {
  76848. material.bind(mesh.getWorldMatrix(), mesh);
  76849. }
  76850. else {
  76851. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76852. // Alpha test
  76853. if (material && material.needAlphaTesting()) {
  76854. var alphaTexture = material.getAlphaTestTexture();
  76855. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76856. if (alphaTexture) {
  76857. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76858. }
  76859. }
  76860. // Bones
  76861. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76862. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76863. }
  76864. }
  76865. // Draw
  76866. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76867. }
  76868. };
  76869. // Render target texture callbacks
  76870. var savedSceneClearColor;
  76871. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76872. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76873. savedSceneClearColor = scene.clearColor;
  76874. scene.clearColor = sceneClearColor;
  76875. });
  76876. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76877. scene.clearColor = savedSceneClearColor;
  76878. });
  76879. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76880. var engine = scene.getEngine();
  76881. var index;
  76882. if (depthOnlySubMeshes.length) {
  76883. engine.setColorWrite(false);
  76884. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76885. renderSubMesh(depthOnlySubMeshes.data[index]);
  76886. }
  76887. engine.setColorWrite(true);
  76888. }
  76889. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76890. renderSubMesh(opaqueSubMeshes.data[index]);
  76891. }
  76892. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76893. renderSubMesh(alphaTestSubMeshes.data[index]);
  76894. }
  76895. if (transparentSubMeshes.length) {
  76896. // Sort sub meshes
  76897. for (index = 0; index < transparentSubMeshes.length; index++) {
  76898. var submesh = transparentSubMeshes.data[index];
  76899. var boundingInfo = submesh.getBoundingInfo();
  76900. if (boundingInfo && scene.activeCamera) {
  76901. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76902. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76903. }
  76904. }
  76905. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76906. sortedArray.sort(function (a, b) {
  76907. // Alpha index first
  76908. if (a._alphaIndex > b._alphaIndex) {
  76909. return 1;
  76910. }
  76911. if (a._alphaIndex < b._alphaIndex) {
  76912. return -1;
  76913. }
  76914. // Then distance to camera
  76915. if (a._distanceToCamera < b._distanceToCamera) {
  76916. return 1;
  76917. }
  76918. if (a._distanceToCamera > b._distanceToCamera) {
  76919. return -1;
  76920. }
  76921. return 0;
  76922. });
  76923. // Render sub meshes
  76924. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76925. for (index = 0; index < sortedArray.length; index++) {
  76926. renderSubMesh(sortedArray[index]);
  76927. }
  76928. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76929. }
  76930. };
  76931. };
  76932. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76933. var transform = scene.getTransformMatrix();
  76934. var meshPosition;
  76935. if (this.useCustomMeshPosition) {
  76936. meshPosition = this.customMeshPosition;
  76937. }
  76938. else if (this.attachedNode) {
  76939. meshPosition = this.attachedNode.position;
  76940. }
  76941. else {
  76942. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76943. }
  76944. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76945. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76946. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76947. if (this.invert)
  76948. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76949. };
  76950. // Static methods
  76951. /**
  76952. * Creates a default mesh for the Volumeric Light Scattering post-process
  76953. * @param {string} The mesh name
  76954. * @param {BABYLON.Scene} The scene where to create the mesh
  76955. * @return {BABYLON.Mesh} the default mesh
  76956. */
  76957. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76958. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76959. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76960. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76961. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76962. mesh.material = material;
  76963. return mesh;
  76964. };
  76965. __decorate([
  76966. BABYLON.serializeAsVector3()
  76967. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76968. __decorate([
  76969. BABYLON.serialize()
  76970. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76971. __decorate([
  76972. BABYLON.serialize()
  76973. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76974. __decorate([
  76975. BABYLON.serializeAsMeshReference()
  76976. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76977. __decorate([
  76978. BABYLON.serialize()
  76979. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76980. __decorate([
  76981. BABYLON.serialize()
  76982. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76983. __decorate([
  76984. BABYLON.serialize()
  76985. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76986. __decorate([
  76987. BABYLON.serialize()
  76988. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76989. __decorate([
  76990. BABYLON.serialize()
  76991. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76992. return VolumetricLightScatteringPostProcess;
  76993. }(BABYLON.PostProcess));
  76994. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76995. })(BABYLON || (BABYLON = {}));
  76996. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76997. //
  76998. // This post-process allows the modification of rendered colors by using
  76999. // a 'look-up table' (LUT). This effect is also called Color Grading.
  77000. //
  77001. // The object needs to be provided an url to a texture containing the color
  77002. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  77003. // Use an image editing software to tweak the LUT to match your needs.
  77004. //
  77005. // For an example of a color LUT, see here:
  77006. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  77007. // For explanations on color grading, see here:
  77008. // http://udn.epicgames.com/Three/ColorGrading.html
  77009. //
  77010. var BABYLON;
  77011. (function (BABYLON) {
  77012. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  77013. __extends(ColorCorrectionPostProcess, _super);
  77014. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  77015. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  77016. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  77017. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  77018. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77019. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77020. _this.onApply = function (effect) {
  77021. effect.setTexture("colorTable", _this._colorTableTexture);
  77022. };
  77023. return _this;
  77024. }
  77025. return ColorCorrectionPostProcess;
  77026. }(BABYLON.PostProcess));
  77027. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77028. })(BABYLON || (BABYLON = {}));
  77029. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77030. var BABYLON;
  77031. (function (BABYLON) {
  77032. /** Defines operator used for tonemapping */
  77033. var TonemappingOperator;
  77034. (function (TonemappingOperator) {
  77035. /** Hable */
  77036. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77037. /** Reinhard */
  77038. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77039. /** HejiDawson */
  77040. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77041. /** Photographic */
  77042. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77043. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77044. ;
  77045. /**
  77046. * Defines a post process to apply tone mapping
  77047. */
  77048. var TonemapPostProcess = /** @class */ (function (_super) {
  77049. __extends(TonemapPostProcess, _super);
  77050. /**
  77051. * Creates a new TonemapPostProcess
  77052. * @param name defines the name of the postprocess
  77053. * @param _operator defines the operator to use
  77054. * @param exposureAdjustment defines the required exposure adjustement
  77055. * @param camera defines the camera to use (can be null)
  77056. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77057. * @param engine defines the hosting engine (can be ignore if camera is set)
  77058. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77059. */
  77060. function TonemapPostProcess(name, _operator,
  77061. /** Defines the required exposure adjustement */
  77062. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77064. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77065. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77066. _this._operator = _operator;
  77067. _this.exposureAdjustment = exposureAdjustment;
  77068. var defines = "#define ";
  77069. if (_this._operator === TonemappingOperator.Hable)
  77070. defines += "HABLE_TONEMAPPING";
  77071. else if (_this._operator === TonemappingOperator.Reinhard)
  77072. defines += "REINHARD_TONEMAPPING";
  77073. else if (_this._operator === TonemappingOperator.HejiDawson)
  77074. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77075. else if (_this._operator === TonemappingOperator.Photographic)
  77076. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77077. //sadly a second call to create the effect.
  77078. _this.updateEffect(defines);
  77079. _this.onApply = function (effect) {
  77080. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77081. };
  77082. return _this;
  77083. }
  77084. return TonemapPostProcess;
  77085. }(BABYLON.PostProcess));
  77086. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77087. })(BABYLON || (BABYLON = {}));
  77088. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77089. var BABYLON;
  77090. (function (BABYLON) {
  77091. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77092. __extends(DisplayPassPostProcess, _super);
  77093. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77094. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77095. }
  77096. return DisplayPassPostProcess;
  77097. }(BABYLON.PostProcess));
  77098. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77099. })(BABYLON || (BABYLON = {}));
  77100. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77101. var BABYLON;
  77102. (function (BABYLON) {
  77103. var HighlightsPostProcess = /** @class */ (function (_super) {
  77104. __extends(HighlightsPostProcess, _super);
  77105. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77106. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77107. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77108. }
  77109. return HighlightsPostProcess;
  77110. }(BABYLON.PostProcess));
  77111. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77112. })(BABYLON || (BABYLON = {}));
  77113. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77114. var BABYLON;
  77115. (function (BABYLON) {
  77116. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77117. __extends(ImageProcessingPostProcess, _super);
  77118. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77119. if (camera === void 0) { camera = null; }
  77120. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77121. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77122. _this._fromLinearSpace = true;
  77123. /**
  77124. * Defines cache preventing GC.
  77125. */
  77126. _this._defines = {
  77127. IMAGEPROCESSING: false,
  77128. VIGNETTE: false,
  77129. VIGNETTEBLENDMODEMULTIPLY: false,
  77130. VIGNETTEBLENDMODEOPAQUE: false,
  77131. TONEMAPPING: false,
  77132. CONTRAST: false,
  77133. COLORCURVES: false,
  77134. COLORGRADING: false,
  77135. COLORGRADING3D: false,
  77136. FROMLINEARSPACE: false,
  77137. SAMPLER3DGREENDEPTH: false,
  77138. SAMPLER3DBGRMAP: false,
  77139. IMAGEPROCESSINGPOSTPROCESS: false,
  77140. EXPOSURE: false,
  77141. };
  77142. // Setup the configuration as forced by the constructor. This would then not force the
  77143. // scene materials output in linear space and let untouched the default forward pass.
  77144. if (imageProcessingConfiguration) {
  77145. imageProcessingConfiguration.applyByPostProcess = true;
  77146. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77147. // This will cause the shader to be compiled
  77148. _this.fromLinearSpace = false;
  77149. }
  77150. // Setup the default processing configuration to the scene.
  77151. else {
  77152. _this._attachImageProcessingConfiguration(null, true);
  77153. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77154. }
  77155. _this.onApply = function (effect) {
  77156. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77157. };
  77158. return _this;
  77159. }
  77160. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77161. /**
  77162. * Gets the image processing configuration used either in this material.
  77163. */
  77164. get: function () {
  77165. return this._imageProcessingConfiguration;
  77166. },
  77167. /**
  77168. * Sets the Default image processing configuration used either in the this material.
  77169. *
  77170. * If sets to null, the scene one is in use.
  77171. */
  77172. set: function (value) {
  77173. this._attachImageProcessingConfiguration(value);
  77174. },
  77175. enumerable: true,
  77176. configurable: true
  77177. });
  77178. /**
  77179. * Attaches a new image processing configuration to the PBR Material.
  77180. * @param configuration
  77181. */
  77182. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77183. var _this = this;
  77184. if (doNotBuild === void 0) { doNotBuild = false; }
  77185. if (configuration === this._imageProcessingConfiguration) {
  77186. return;
  77187. }
  77188. // Detaches observer.
  77189. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77190. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77191. }
  77192. // Pick the scene configuration if needed.
  77193. if (!configuration) {
  77194. var scene = null;
  77195. var engine = this.getEngine();
  77196. var camera = this.getCamera();
  77197. if (camera) {
  77198. scene = camera.getScene();
  77199. }
  77200. else if (engine && engine.scenes) {
  77201. var scenes = engine.scenes;
  77202. scene = scenes[scenes.length - 1];
  77203. }
  77204. else {
  77205. scene = BABYLON.Engine.LastCreatedScene;
  77206. }
  77207. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77208. }
  77209. else {
  77210. this._imageProcessingConfiguration = configuration;
  77211. }
  77212. // Attaches observer.
  77213. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77214. _this._updateParameters();
  77215. });
  77216. // Ensure the effect will be rebuilt.
  77217. if (!doNotBuild) {
  77218. this._updateParameters();
  77219. }
  77220. };
  77221. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77222. /**
  77223. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77224. */
  77225. get: function () {
  77226. return this.imageProcessingConfiguration.colorCurves;
  77227. },
  77228. /**
  77229. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77230. */
  77231. set: function (value) {
  77232. this.imageProcessingConfiguration.colorCurves = value;
  77233. },
  77234. enumerable: true,
  77235. configurable: true
  77236. });
  77237. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77238. /**
  77239. * Gets wether the color curves effect is enabled.
  77240. */
  77241. get: function () {
  77242. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77243. },
  77244. /**
  77245. * Sets wether the color curves effect is enabled.
  77246. */
  77247. set: function (value) {
  77248. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77249. },
  77250. enumerable: true,
  77251. configurable: true
  77252. });
  77253. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77254. /**
  77255. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77256. */
  77257. get: function () {
  77258. return this.imageProcessingConfiguration.colorGradingTexture;
  77259. },
  77260. /**
  77261. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77262. */
  77263. set: function (value) {
  77264. this.imageProcessingConfiguration.colorGradingTexture = value;
  77265. },
  77266. enumerable: true,
  77267. configurable: true
  77268. });
  77269. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77270. /**
  77271. * Gets wether the color grading effect is enabled.
  77272. */
  77273. get: function () {
  77274. return this.imageProcessingConfiguration.colorGradingEnabled;
  77275. },
  77276. /**
  77277. * Gets wether the color grading effect is enabled.
  77278. */
  77279. set: function (value) {
  77280. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77281. },
  77282. enumerable: true,
  77283. configurable: true
  77284. });
  77285. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77286. /**
  77287. * Gets exposure used in the effect.
  77288. */
  77289. get: function () {
  77290. return this.imageProcessingConfiguration.exposure;
  77291. },
  77292. /**
  77293. * Sets exposure used in the effect.
  77294. */
  77295. set: function (value) {
  77296. this.imageProcessingConfiguration.exposure = value;
  77297. },
  77298. enumerable: true,
  77299. configurable: true
  77300. });
  77301. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77302. /**
  77303. * Gets wether tonemapping is enabled or not.
  77304. */
  77305. get: function () {
  77306. return this._imageProcessingConfiguration.toneMappingEnabled;
  77307. },
  77308. /**
  77309. * Sets wether tonemapping is enabled or not
  77310. */
  77311. set: function (value) {
  77312. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77313. },
  77314. enumerable: true,
  77315. configurable: true
  77316. });
  77317. ;
  77318. ;
  77319. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77320. /**
  77321. * Gets contrast used in the effect.
  77322. */
  77323. get: function () {
  77324. return this.imageProcessingConfiguration.contrast;
  77325. },
  77326. /**
  77327. * Sets contrast used in the effect.
  77328. */
  77329. set: function (value) {
  77330. this.imageProcessingConfiguration.contrast = value;
  77331. },
  77332. enumerable: true,
  77333. configurable: true
  77334. });
  77335. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77336. /**
  77337. * Gets Vignette stretch size.
  77338. */
  77339. get: function () {
  77340. return this.imageProcessingConfiguration.vignetteStretch;
  77341. },
  77342. /**
  77343. * Sets Vignette stretch size.
  77344. */
  77345. set: function (value) {
  77346. this.imageProcessingConfiguration.vignetteStretch = value;
  77347. },
  77348. enumerable: true,
  77349. configurable: true
  77350. });
  77351. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77352. /**
  77353. * Gets Vignette centre X Offset.
  77354. */
  77355. get: function () {
  77356. return this.imageProcessingConfiguration.vignetteCentreX;
  77357. },
  77358. /**
  77359. * Sets Vignette centre X Offset.
  77360. */
  77361. set: function (value) {
  77362. this.imageProcessingConfiguration.vignetteCentreX = value;
  77363. },
  77364. enumerable: true,
  77365. configurable: true
  77366. });
  77367. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77368. /**
  77369. * Gets Vignette centre Y Offset.
  77370. */
  77371. get: function () {
  77372. return this.imageProcessingConfiguration.vignetteCentreY;
  77373. },
  77374. /**
  77375. * Sets Vignette centre Y Offset.
  77376. */
  77377. set: function (value) {
  77378. this.imageProcessingConfiguration.vignetteCentreY = value;
  77379. },
  77380. enumerable: true,
  77381. configurable: true
  77382. });
  77383. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77384. /**
  77385. * Gets Vignette weight or intensity of the vignette effect.
  77386. */
  77387. get: function () {
  77388. return this.imageProcessingConfiguration.vignetteWeight;
  77389. },
  77390. /**
  77391. * Sets Vignette weight or intensity of the vignette effect.
  77392. */
  77393. set: function (value) {
  77394. this.imageProcessingConfiguration.vignetteWeight = value;
  77395. },
  77396. enumerable: true,
  77397. configurable: true
  77398. });
  77399. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77400. /**
  77401. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77402. * if vignetteEnabled is set to true.
  77403. */
  77404. get: function () {
  77405. return this.imageProcessingConfiguration.vignetteColor;
  77406. },
  77407. /**
  77408. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77409. * if vignetteEnabled is set to true.
  77410. */
  77411. set: function (value) {
  77412. this.imageProcessingConfiguration.vignetteColor = value;
  77413. },
  77414. enumerable: true,
  77415. configurable: true
  77416. });
  77417. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77418. /**
  77419. * Gets Camera field of view used by the Vignette effect.
  77420. */
  77421. get: function () {
  77422. return this.imageProcessingConfiguration.vignetteCameraFov;
  77423. },
  77424. /**
  77425. * Sets Camera field of view used by the Vignette effect.
  77426. */
  77427. set: function (value) {
  77428. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77429. },
  77430. enumerable: true,
  77431. configurable: true
  77432. });
  77433. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77434. /**
  77435. * Gets the vignette blend mode allowing different kind of effect.
  77436. */
  77437. get: function () {
  77438. return this.imageProcessingConfiguration.vignetteBlendMode;
  77439. },
  77440. /**
  77441. * Sets the vignette blend mode allowing different kind of effect.
  77442. */
  77443. set: function (value) {
  77444. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77445. },
  77446. enumerable: true,
  77447. configurable: true
  77448. });
  77449. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77450. /**
  77451. * Gets wether the vignette effect is enabled.
  77452. */
  77453. get: function () {
  77454. return this.imageProcessingConfiguration.vignetteEnabled;
  77455. },
  77456. /**
  77457. * Sets wether the vignette effect is enabled.
  77458. */
  77459. set: function (value) {
  77460. this.imageProcessingConfiguration.vignetteEnabled = value;
  77461. },
  77462. enumerable: true,
  77463. configurable: true
  77464. });
  77465. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77466. /**
  77467. * Gets wether the input of the processing is in Gamma or Linear Space.
  77468. */
  77469. get: function () {
  77470. return this._fromLinearSpace;
  77471. },
  77472. /**
  77473. * Sets wether the input of the processing is in Gamma or Linear Space.
  77474. */
  77475. set: function (value) {
  77476. if (this._fromLinearSpace === value) {
  77477. return;
  77478. }
  77479. this._fromLinearSpace = value;
  77480. this._updateParameters();
  77481. },
  77482. enumerable: true,
  77483. configurable: true
  77484. });
  77485. ImageProcessingPostProcess.prototype.getClassName = function () {
  77486. return "ImageProcessingPostProcess";
  77487. };
  77488. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77489. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77490. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77491. var defines = "";
  77492. for (var define in this._defines) {
  77493. if (this._defines[define]) {
  77494. defines += "#define " + define + ";\r\n";
  77495. }
  77496. }
  77497. var samplers = ["textureSampler"];
  77498. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77499. var uniforms = ["scale"];
  77500. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77501. this.updateEffect(defines, uniforms, samplers);
  77502. };
  77503. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77504. _super.prototype.dispose.call(this, camera);
  77505. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77506. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77507. }
  77508. this.imageProcessingConfiguration.applyByPostProcess = false;
  77509. };
  77510. __decorate([
  77511. BABYLON.serialize()
  77512. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77513. return ImageProcessingPostProcess;
  77514. }(BABYLON.PostProcess));
  77515. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77516. })(BABYLON || (BABYLON = {}));
  77517. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77518. var BABYLON;
  77519. (function (BABYLON) {
  77520. /**
  77521. * Class used to store bone information
  77522. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77523. */
  77524. var Bone = /** @class */ (function (_super) {
  77525. __extends(Bone, _super);
  77526. /**
  77527. * Create a new bone
  77528. * @param name defines the bone name
  77529. * @param skeleton defines the parent skeleton
  77530. * @param parentBone defines the parent (can be null if the bone is the root)
  77531. * @param localMatrix defines the local matrix
  77532. * @param restPose defines the rest pose matrix
  77533. * @param baseMatrix defines the base matrix
  77534. * @param index defines index of the bone in the hiearchy
  77535. */
  77536. function Bone(
  77537. /**
  77538. * defines the bone name
  77539. */
  77540. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77541. if (parentBone === void 0) { parentBone = null; }
  77542. if (localMatrix === void 0) { localMatrix = null; }
  77543. if (restPose === void 0) { restPose = null; }
  77544. if (baseMatrix === void 0) { baseMatrix = null; }
  77545. if (index === void 0) { index = null; }
  77546. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77547. _this.name = name;
  77548. /**
  77549. * Gets the list of child bones
  77550. */
  77551. _this.children = new Array();
  77552. /** Gets the animations associated with this bone */
  77553. _this.animations = new Array();
  77554. /**
  77555. * @hidden Internal only
  77556. * Set this value to map this bone to a different index in the transform matrices
  77557. * Set this value to -1 to exclude the bone from the transform matrices
  77558. */
  77559. _this._index = null;
  77560. _this._absoluteTransform = new BABYLON.Matrix();
  77561. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77562. _this._scalingDeterminant = 1;
  77563. _this._worldTransform = new BABYLON.Matrix();
  77564. _this._needToDecompose = true;
  77565. _this._needToCompose = false;
  77566. _this._skeleton = skeleton;
  77567. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77568. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77569. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77570. _this._index = index;
  77571. skeleton.bones.push(_this);
  77572. _this.setParent(parentBone, false);
  77573. if (baseMatrix || localMatrix) {
  77574. _this._updateDifferenceMatrix();
  77575. }
  77576. return _this;
  77577. }
  77578. Object.defineProperty(Bone.prototype, "_matrix", {
  77579. /** @hidden */
  77580. get: function () {
  77581. this._compose();
  77582. return this._localMatrix;
  77583. },
  77584. /** @hidden */
  77585. set: function (value) {
  77586. this._localMatrix.copyFrom(value);
  77587. this._needToDecompose = true;
  77588. },
  77589. enumerable: true,
  77590. configurable: true
  77591. });
  77592. // Members
  77593. /**
  77594. * Gets the parent skeleton
  77595. * @returns a skeleton
  77596. */
  77597. Bone.prototype.getSkeleton = function () {
  77598. return this._skeleton;
  77599. };
  77600. /**
  77601. * Gets parent bone
  77602. * @returns a bone or null if the bone is the root of the bone hierarchy
  77603. */
  77604. Bone.prototype.getParent = function () {
  77605. return this._parent;
  77606. };
  77607. /**
  77608. * Sets the parent bone
  77609. * @param parent defines the parent (can be null if the bone is the root)
  77610. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77611. */
  77612. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77613. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77614. if (this._parent === parent) {
  77615. return;
  77616. }
  77617. if (this._parent) {
  77618. var index = this._parent.children.indexOf(this);
  77619. if (index !== -1) {
  77620. this._parent.children.splice(index, 1);
  77621. }
  77622. }
  77623. this._parent = parent;
  77624. if (this._parent) {
  77625. this._parent.children.push(this);
  77626. }
  77627. if (updateDifferenceMatrix) {
  77628. this._updateDifferenceMatrix();
  77629. }
  77630. this.markAsDirty();
  77631. };
  77632. /**
  77633. * Gets the local matrix
  77634. * @returns a matrix
  77635. */
  77636. Bone.prototype.getLocalMatrix = function () {
  77637. this._compose();
  77638. return this._localMatrix;
  77639. };
  77640. /**
  77641. * Gets the base matrix (initial matrix which remains unchanged)
  77642. * @returns a matrix
  77643. */
  77644. Bone.prototype.getBaseMatrix = function () {
  77645. return this._baseMatrix;
  77646. };
  77647. /**
  77648. * Gets the rest pose matrix
  77649. * @returns a matrix
  77650. */
  77651. Bone.prototype.getRestPose = function () {
  77652. return this._restPose;
  77653. };
  77654. /**
  77655. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77656. */
  77657. Bone.prototype.getWorldMatrix = function () {
  77658. return this._worldTransform;
  77659. };
  77660. /**
  77661. * Sets the local matrix to rest pose matrix
  77662. */
  77663. Bone.prototype.returnToRest = function () {
  77664. this.updateMatrix(this._restPose.clone());
  77665. };
  77666. /**
  77667. * Gets the inverse of the absolute transform matrix.
  77668. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77669. * @returns a matrix
  77670. */
  77671. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77672. return this._invertedAbsoluteTransform;
  77673. };
  77674. /**
  77675. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77676. * @returns a matrix
  77677. */
  77678. Bone.prototype.getAbsoluteTransform = function () {
  77679. return this._absoluteTransform;
  77680. };
  77681. Object.defineProperty(Bone.prototype, "position", {
  77682. // Properties (matches AbstractMesh properties)
  77683. /** Gets or sets current position (in local space) */
  77684. get: function () {
  77685. this._decompose();
  77686. return this._localPosition;
  77687. },
  77688. set: function (newPosition) {
  77689. this._decompose();
  77690. this._localPosition.copyFrom(newPosition);
  77691. this._markAsDirtyAndCompose();
  77692. },
  77693. enumerable: true,
  77694. configurable: true
  77695. });
  77696. Object.defineProperty(Bone.prototype, "rotation", {
  77697. /** Gets or sets current rotation (in local space) */
  77698. get: function () {
  77699. return this.getRotation();
  77700. },
  77701. set: function (newRotation) {
  77702. this.setRotation(newRotation);
  77703. },
  77704. enumerable: true,
  77705. configurable: true
  77706. });
  77707. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77708. /** Gets or sets current rotation quaternion (in local space) */
  77709. get: function () {
  77710. this._decompose();
  77711. return this._localRotation;
  77712. },
  77713. set: function (newRotation) {
  77714. this.setRotationQuaternion(newRotation);
  77715. },
  77716. enumerable: true,
  77717. configurable: true
  77718. });
  77719. Object.defineProperty(Bone.prototype, "scaling", {
  77720. /** Gets or sets current scaling (in local space) */
  77721. get: function () {
  77722. return this.getScale();
  77723. },
  77724. set: function (newScaling) {
  77725. this.setScale(newScaling);
  77726. },
  77727. enumerable: true,
  77728. configurable: true
  77729. });
  77730. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77731. /**
  77732. * Gets the animation properties override
  77733. */
  77734. get: function () {
  77735. return this._skeleton.animationPropertiesOverride;
  77736. },
  77737. enumerable: true,
  77738. configurable: true
  77739. });
  77740. // Methods
  77741. Bone.prototype._decompose = function () {
  77742. if (!this._needToDecompose) {
  77743. return;
  77744. }
  77745. this._needToDecompose = false;
  77746. if (!this._localScaling) {
  77747. this._localScaling = BABYLON.Vector3.Zero();
  77748. this._localRotation = BABYLON.Quaternion.Zero();
  77749. this._localPosition = BABYLON.Vector3.Zero();
  77750. }
  77751. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77752. };
  77753. Bone.prototype._compose = function () {
  77754. if (!this._needToCompose) {
  77755. return;
  77756. }
  77757. this._needToCompose = false;
  77758. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77759. };
  77760. /**
  77761. * Update the base and local matrices
  77762. * @param matrix defines the new base or local matrix
  77763. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77764. * @param updateLocalMatrix defines if the local matrix should be updated
  77765. */
  77766. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77767. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77768. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77769. this._baseMatrix.copyFrom(matrix);
  77770. if (updateDifferenceMatrix) {
  77771. this._updateDifferenceMatrix();
  77772. }
  77773. if (updateLocalMatrix) {
  77774. this._localMatrix.copyFrom(matrix);
  77775. this._markAsDirtyAndDecompose();
  77776. }
  77777. else {
  77778. this.markAsDirty();
  77779. }
  77780. };
  77781. /** @hidden */
  77782. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77783. if (updateChildren === void 0) { updateChildren = true; }
  77784. if (!rootMatrix) {
  77785. rootMatrix = this._baseMatrix;
  77786. }
  77787. if (this._parent) {
  77788. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77789. }
  77790. else {
  77791. this._absoluteTransform.copyFrom(rootMatrix);
  77792. }
  77793. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77794. if (updateChildren) {
  77795. for (var index = 0; index < this.children.length; index++) {
  77796. this.children[index]._updateDifferenceMatrix();
  77797. }
  77798. }
  77799. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77800. };
  77801. /**
  77802. * Flag the bone as dirty (Forcing it to update everything)
  77803. */
  77804. Bone.prototype.markAsDirty = function () {
  77805. this._currentRenderId++;
  77806. this._childRenderId++;
  77807. this._skeleton._markAsDirty();
  77808. };
  77809. Bone.prototype._markAsDirtyAndCompose = function () {
  77810. this.markAsDirty();
  77811. this._needToCompose = true;
  77812. };
  77813. Bone.prototype._markAsDirtyAndDecompose = function () {
  77814. this.markAsDirty();
  77815. this._needToDecompose = true;
  77816. };
  77817. /**
  77818. * Copy an animation range from another bone
  77819. * @param source defines the source bone
  77820. * @param rangeName defines the range name to copy
  77821. * @param frameOffset defines the frame offset
  77822. * @param rescaleAsRequired defines if rescaling must be applied if required
  77823. * @param skelDimensionsRatio defines the scaling ratio
  77824. * @returns true if operation was successful
  77825. */
  77826. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77827. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77828. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77829. // all animation may be coming from a library skeleton, so may need to create animation
  77830. if (this.animations.length === 0) {
  77831. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77832. this.animations[0].setKeys([]);
  77833. }
  77834. // get animation info / verify there is such a range from the source bone
  77835. var sourceRange = source.animations[0].getRange(rangeName);
  77836. if (!sourceRange) {
  77837. return false;
  77838. }
  77839. var from = sourceRange.from;
  77840. var to = sourceRange.to;
  77841. var sourceKeys = source.animations[0].getKeys();
  77842. // rescaling prep
  77843. var sourceBoneLength = source.length;
  77844. var sourceParent = source.getParent();
  77845. var parent = this.getParent();
  77846. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77847. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77848. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77849. var destKeys = this.animations[0].getKeys();
  77850. // loop vars declaration
  77851. var orig;
  77852. var origTranslation;
  77853. var mat;
  77854. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77855. orig = sourceKeys[key];
  77856. if (orig.frame >= from && orig.frame <= to) {
  77857. if (rescaleAsRequired) {
  77858. mat = orig.value.clone();
  77859. // scale based on parent ratio, when bone has parent
  77860. if (parentScalingReqd) {
  77861. origTranslation = mat.getTranslation();
  77862. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77863. // scale based on skeleton dimension ratio when root bone, and value is passed
  77864. }
  77865. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77866. origTranslation = mat.getTranslation();
  77867. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77868. // use original when root bone, and no data for skelDimensionsRatio
  77869. }
  77870. else {
  77871. mat = orig.value;
  77872. }
  77873. }
  77874. else {
  77875. mat = orig.value;
  77876. }
  77877. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77878. }
  77879. }
  77880. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77881. return true;
  77882. };
  77883. /**
  77884. * Translate the bone in local or world space
  77885. * @param vec The amount to translate the bone
  77886. * @param space The space that the translation is in
  77887. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77888. */
  77889. Bone.prototype.translate = function (vec, space, mesh) {
  77890. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77891. var lm = this.getLocalMatrix();
  77892. if (space == BABYLON.Space.LOCAL) {
  77893. lm.m[12] += vec.x;
  77894. lm.m[13] += vec.y;
  77895. lm.m[14] += vec.z;
  77896. }
  77897. else {
  77898. var wm = null;
  77899. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77900. if (mesh) {
  77901. wm = mesh.getWorldMatrix();
  77902. }
  77903. this._skeleton.computeAbsoluteTransforms();
  77904. var tmat = Bone._tmpMats[0];
  77905. var tvec = Bone._tmpVecs[0];
  77906. if (this._parent) {
  77907. if (mesh && wm) {
  77908. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77909. tmat.multiplyToRef(wm, tmat);
  77910. }
  77911. else {
  77912. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77913. }
  77914. }
  77915. tmat.m[12] = 0;
  77916. tmat.m[13] = 0;
  77917. tmat.m[14] = 0;
  77918. tmat.invert();
  77919. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77920. lm.m[12] += tvec.x;
  77921. lm.m[13] += tvec.y;
  77922. lm.m[14] += tvec.z;
  77923. }
  77924. this._markAsDirtyAndDecompose();
  77925. };
  77926. /**
  77927. * Set the postion of the bone in local or world space
  77928. * @param position The position to set the bone
  77929. * @param space The space that the position is in
  77930. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77931. */
  77932. Bone.prototype.setPosition = function (position, space, mesh) {
  77933. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77934. var lm = this.getLocalMatrix();
  77935. if (space == BABYLON.Space.LOCAL) {
  77936. lm.m[12] = position.x;
  77937. lm.m[13] = position.y;
  77938. lm.m[14] = position.z;
  77939. }
  77940. else {
  77941. var wm = null;
  77942. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77943. if (mesh) {
  77944. wm = mesh.getWorldMatrix();
  77945. }
  77946. this._skeleton.computeAbsoluteTransforms();
  77947. var tmat = Bone._tmpMats[0];
  77948. var vec = Bone._tmpVecs[0];
  77949. if (this._parent) {
  77950. if (mesh && wm) {
  77951. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77952. tmat.multiplyToRef(wm, tmat);
  77953. }
  77954. else {
  77955. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77956. }
  77957. }
  77958. tmat.invert();
  77959. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77960. lm.m[12] = vec.x;
  77961. lm.m[13] = vec.y;
  77962. lm.m[14] = vec.z;
  77963. }
  77964. this._markAsDirtyAndDecompose();
  77965. };
  77966. /**
  77967. * Set the absolute position of the bone (world space)
  77968. * @param position The position to set the bone
  77969. * @param mesh The mesh that this bone is attached to
  77970. */
  77971. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77972. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77973. };
  77974. /**
  77975. * Scale the bone on the x, y and z axes (in local space)
  77976. * @param x The amount to scale the bone on the x axis
  77977. * @param y The amount to scale the bone on the y axis
  77978. * @param z The amount to scale the bone on the z axis
  77979. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77980. */
  77981. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77982. if (scaleChildren === void 0) { scaleChildren = false; }
  77983. var locMat = this.getLocalMatrix();
  77984. // Apply new scaling on top of current local matrix
  77985. var scaleMat = Bone._tmpMats[0];
  77986. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77987. scaleMat.multiplyToRef(locMat, locMat);
  77988. // Invert scaling matrix and apply the inverse to all children
  77989. scaleMat.invert();
  77990. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77991. var child = _a[_i];
  77992. var cm = child.getLocalMatrix();
  77993. cm.multiplyToRef(scaleMat, cm);
  77994. cm.m[12] *= x;
  77995. cm.m[13] *= y;
  77996. cm.m[14] *= z;
  77997. child._markAsDirtyAndDecompose();
  77998. }
  77999. this._markAsDirtyAndDecompose();
  78000. if (scaleChildren) {
  78001. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  78002. var child = _c[_b];
  78003. child.scale(x, y, z, scaleChildren);
  78004. }
  78005. }
  78006. };
  78007. /**
  78008. * Set the bone scaling in local space
  78009. * @param scale defines the scaling vector
  78010. */
  78011. Bone.prototype.setScale = function (scale) {
  78012. this._decompose();
  78013. this._localScaling.copyFrom(scale);
  78014. this._markAsDirtyAndCompose();
  78015. };
  78016. /**
  78017. * Gets the current scaling in local space
  78018. * @returns the current scaling vector
  78019. */
  78020. Bone.prototype.getScale = function () {
  78021. this._decompose();
  78022. return this._localScaling;
  78023. };
  78024. /**
  78025. * Gets the current scaling in local space and stores it in a target vector
  78026. * @param result defines the target vector
  78027. */
  78028. Bone.prototype.getScaleToRef = function (result) {
  78029. this._decompose();
  78030. result.copyFrom(this._localScaling);
  78031. };
  78032. /**
  78033. * Set the yaw, pitch, and roll of the bone in local or world space
  78034. * @param yaw The rotation of the bone on the y axis
  78035. * @param pitch The rotation of the bone on the x axis
  78036. * @param roll The rotation of the bone on the z axis
  78037. * @param space The space that the axes of rotation are in
  78038. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78039. */
  78040. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78042. if (space === BABYLON.Space.LOCAL) {
  78043. var quat = Bone._tmpQuat;
  78044. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78045. this.setRotationQuaternion(quat, space, mesh);
  78046. return;
  78047. }
  78048. var rotMatInv = Bone._tmpMats[0];
  78049. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78050. return;
  78051. }
  78052. var rotMat = Bone._tmpMats[1];
  78053. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78054. rotMatInv.multiplyToRef(rotMat, rotMat);
  78055. this._rotateWithMatrix(rotMat, space, mesh);
  78056. };
  78057. /**
  78058. * Add a rotation to the bone on an axis in local or world space
  78059. * @param axis The axis to rotate the bone on
  78060. * @param amount The amount to rotate the bone
  78061. * @param space The space that the axis is in
  78062. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78063. */
  78064. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78065. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78066. var rmat = Bone._tmpMats[0];
  78067. rmat.m[12] = 0;
  78068. rmat.m[13] = 0;
  78069. rmat.m[14] = 0;
  78070. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78071. this._rotateWithMatrix(rmat, space, mesh);
  78072. };
  78073. /**
  78074. * Set the rotation of the bone to a particular axis angle in local or world space
  78075. * @param axis The axis to rotate the bone on
  78076. * @param angle The angle that the bone should be rotated to
  78077. * @param space The space that the axis is in
  78078. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78079. */
  78080. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78081. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78082. if (space === BABYLON.Space.LOCAL) {
  78083. var quat = Bone._tmpQuat;
  78084. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78085. this.setRotationQuaternion(quat, space, mesh);
  78086. return;
  78087. }
  78088. var rotMatInv = Bone._tmpMats[0];
  78089. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78090. return;
  78091. }
  78092. var rotMat = Bone._tmpMats[1];
  78093. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78094. rotMatInv.multiplyToRef(rotMat, rotMat);
  78095. this._rotateWithMatrix(rotMat, space, mesh);
  78096. };
  78097. /**
  78098. * Set the euler rotation of the bone in local of world space
  78099. * @param rotation The euler rotation that the bone should be set to
  78100. * @param space The space that the rotation is in
  78101. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78102. */
  78103. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78104. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78105. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78106. };
  78107. /**
  78108. * Set the quaternion rotation of the bone in local of world space
  78109. * @param quat The quaternion rotation that the bone should be set to
  78110. * @param space The space that the rotation is in
  78111. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78112. */
  78113. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78114. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78115. if (space === BABYLON.Space.LOCAL) {
  78116. this._decompose();
  78117. this._localRotation.copyFrom(quat);
  78118. this._markAsDirtyAndCompose();
  78119. return;
  78120. }
  78121. var rotMatInv = Bone._tmpMats[0];
  78122. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78123. return;
  78124. }
  78125. var rotMat = Bone._tmpMats[1];
  78126. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78127. rotMatInv.multiplyToRef(rotMat, rotMat);
  78128. this._rotateWithMatrix(rotMat, space, mesh);
  78129. };
  78130. /**
  78131. * Set the rotation matrix of the bone in local of world space
  78132. * @param rotMat The rotation matrix that the bone should be set to
  78133. * @param space The space that the rotation is in
  78134. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78135. */
  78136. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78137. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78138. if (space === BABYLON.Space.LOCAL) {
  78139. var quat = Bone._tmpQuat;
  78140. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78141. this.setRotationQuaternion(quat, space, mesh);
  78142. return;
  78143. }
  78144. var rotMatInv = Bone._tmpMats[0];
  78145. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78146. return;
  78147. }
  78148. var rotMat2 = Bone._tmpMats[1];
  78149. rotMat2.copyFrom(rotMat);
  78150. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78151. this._rotateWithMatrix(rotMat2, space, mesh);
  78152. };
  78153. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78154. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78155. var lmat = this.getLocalMatrix();
  78156. var lx = lmat.m[12];
  78157. var ly = lmat.m[13];
  78158. var lz = lmat.m[14];
  78159. var parent = this.getParent();
  78160. var parentScale = Bone._tmpMats[3];
  78161. var parentScaleInv = Bone._tmpMats[4];
  78162. if (parent && space == BABYLON.Space.WORLD) {
  78163. if (mesh) {
  78164. parentScale.copyFrom(mesh.getWorldMatrix());
  78165. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78166. }
  78167. else {
  78168. parentScale.copyFrom(parent.getAbsoluteTransform());
  78169. }
  78170. parentScaleInv.copyFrom(parentScale);
  78171. parentScaleInv.invert();
  78172. lmat.multiplyToRef(parentScale, lmat);
  78173. lmat.multiplyToRef(rmat, lmat);
  78174. lmat.multiplyToRef(parentScaleInv, lmat);
  78175. }
  78176. else {
  78177. if (space == BABYLON.Space.WORLD && mesh) {
  78178. parentScale.copyFrom(mesh.getWorldMatrix());
  78179. parentScaleInv.copyFrom(parentScale);
  78180. parentScaleInv.invert();
  78181. lmat.multiplyToRef(parentScale, lmat);
  78182. lmat.multiplyToRef(rmat, lmat);
  78183. lmat.multiplyToRef(parentScaleInv, lmat);
  78184. }
  78185. else {
  78186. lmat.multiplyToRef(rmat, lmat);
  78187. }
  78188. }
  78189. lmat.m[12] = lx;
  78190. lmat.m[13] = ly;
  78191. lmat.m[14] = lz;
  78192. this.computeAbsoluteTransforms();
  78193. this._markAsDirtyAndDecompose();
  78194. };
  78195. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78196. var scaleMatrix = Bone._tmpMats[2];
  78197. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78198. if (mesh) {
  78199. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78200. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78201. }
  78202. rotMatInv.invert();
  78203. if (isNaN(rotMatInv.m[0])) {
  78204. // Matrix failed to invert.
  78205. // This can happen if scale is zero for example.
  78206. return false;
  78207. }
  78208. scaleMatrix.m[0] *= this._scalingDeterminant;
  78209. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78210. return true;
  78211. };
  78212. /**
  78213. * Get the position of the bone in local or world space
  78214. * @param space The space that the returned position is in
  78215. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78216. * @returns The position of the bone
  78217. */
  78218. Bone.prototype.getPosition = function (space, mesh) {
  78219. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78220. if (mesh === void 0) { mesh = null; }
  78221. var pos = BABYLON.Vector3.Zero();
  78222. this.getPositionToRef(space, mesh, pos);
  78223. return pos;
  78224. };
  78225. /**
  78226. * Copy the position of the bone to a vector3 in local or world space
  78227. * @param space The space that the returned position is in
  78228. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78229. * @param result The vector3 to copy the position to
  78230. */
  78231. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78232. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78233. if (space == BABYLON.Space.LOCAL) {
  78234. var lm = this.getLocalMatrix();
  78235. result.x = lm.m[12];
  78236. result.y = lm.m[13];
  78237. result.z = lm.m[14];
  78238. }
  78239. else {
  78240. var wm = null;
  78241. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78242. if (mesh) {
  78243. wm = mesh.getWorldMatrix();
  78244. }
  78245. this._skeleton.computeAbsoluteTransforms();
  78246. var tmat = Bone._tmpMats[0];
  78247. if (mesh && wm) {
  78248. tmat.copyFrom(this.getAbsoluteTransform());
  78249. tmat.multiplyToRef(wm, tmat);
  78250. }
  78251. else {
  78252. tmat = this.getAbsoluteTransform();
  78253. }
  78254. result.x = tmat.m[12];
  78255. result.y = tmat.m[13];
  78256. result.z = tmat.m[14];
  78257. }
  78258. };
  78259. /**
  78260. * Get the absolute position of the bone (world space)
  78261. * @param mesh The mesh that this bone is attached to
  78262. * @returns The absolute position of the bone
  78263. */
  78264. Bone.prototype.getAbsolutePosition = function (mesh) {
  78265. if (mesh === void 0) { mesh = null; }
  78266. var pos = BABYLON.Vector3.Zero();
  78267. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78268. return pos;
  78269. };
  78270. /**
  78271. * Copy the absolute position of the bone (world space) to the result param
  78272. * @param mesh The mesh that this bone is attached to
  78273. * @param result The vector3 to copy the absolute position to
  78274. */
  78275. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78276. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78277. };
  78278. /**
  78279. * Compute the absolute transforms of this bone and its children
  78280. */
  78281. Bone.prototype.computeAbsoluteTransforms = function () {
  78282. this._compose();
  78283. if (this._parent) {
  78284. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78285. }
  78286. else {
  78287. this._absoluteTransform.copyFrom(this._localMatrix);
  78288. var poseMatrix = this._skeleton.getPoseMatrix();
  78289. if (poseMatrix) {
  78290. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78291. }
  78292. }
  78293. var children = this.children;
  78294. var len = children.length;
  78295. for (var i = 0; i < len; i++) {
  78296. children[i].computeAbsoluteTransforms();
  78297. }
  78298. };
  78299. /**
  78300. * Get the world direction from an axis that is in the local space of the bone
  78301. * @param localAxis The local direction that is used to compute the world direction
  78302. * @param mesh The mesh that this bone is attached to
  78303. * @returns The world direction
  78304. */
  78305. Bone.prototype.getDirection = function (localAxis, mesh) {
  78306. if (mesh === void 0) { mesh = null; }
  78307. var result = BABYLON.Vector3.Zero();
  78308. this.getDirectionToRef(localAxis, mesh, result);
  78309. return result;
  78310. };
  78311. /**
  78312. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78313. * @param localAxis The local direction that is used to compute the world direction
  78314. * @param mesh The mesh that this bone is attached to
  78315. * @param result The vector3 that the world direction will be copied to
  78316. */
  78317. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78318. if (mesh === void 0) { mesh = null; }
  78319. var wm = null;
  78320. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78321. if (mesh) {
  78322. wm = mesh.getWorldMatrix();
  78323. }
  78324. this._skeleton.computeAbsoluteTransforms();
  78325. var mat = Bone._tmpMats[0];
  78326. mat.copyFrom(this.getAbsoluteTransform());
  78327. if (mesh && wm) {
  78328. mat.multiplyToRef(wm, mat);
  78329. }
  78330. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78331. result.normalize();
  78332. };
  78333. /**
  78334. * Get the euler rotation of the bone in local or world space
  78335. * @param space The space that the rotation should be in
  78336. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78337. * @returns The euler rotation
  78338. */
  78339. Bone.prototype.getRotation = function (space, mesh) {
  78340. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78341. if (mesh === void 0) { mesh = null; }
  78342. var result = BABYLON.Vector3.Zero();
  78343. this.getRotationToRef(space, mesh, result);
  78344. return result;
  78345. };
  78346. /**
  78347. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78348. * @param space The space that the rotation should be in
  78349. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78350. * @param result The vector3 that the rotation should be copied to
  78351. */
  78352. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78354. if (mesh === void 0) { mesh = null; }
  78355. var quat = Bone._tmpQuat;
  78356. this.getRotationQuaternionToRef(space, mesh, quat);
  78357. quat.toEulerAnglesToRef(result);
  78358. };
  78359. /**
  78360. * Get the quaternion rotation of the bone in either local or world space
  78361. * @param space The space that the rotation should be in
  78362. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78363. * @returns The quaternion rotation
  78364. */
  78365. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78366. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78367. if (mesh === void 0) { mesh = null; }
  78368. var result = BABYLON.Quaternion.Identity();
  78369. this.getRotationQuaternionToRef(space, mesh, result);
  78370. return result;
  78371. };
  78372. /**
  78373. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78374. * @param space The space that the rotation should be in
  78375. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78376. * @param result The quaternion that the rotation should be copied to
  78377. */
  78378. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78379. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78380. if (mesh === void 0) { mesh = null; }
  78381. if (space == BABYLON.Space.LOCAL) {
  78382. this._decompose();
  78383. result.copyFrom(this._localRotation);
  78384. }
  78385. else {
  78386. var mat = Bone._tmpMats[0];
  78387. var amat = this.getAbsoluteTransform();
  78388. if (mesh) {
  78389. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78390. }
  78391. else {
  78392. mat.copyFrom(amat);
  78393. }
  78394. mat.m[0] *= this._scalingDeterminant;
  78395. mat.m[1] *= this._scalingDeterminant;
  78396. mat.m[2] *= this._scalingDeterminant;
  78397. mat.decompose(undefined, result, undefined);
  78398. }
  78399. };
  78400. /**
  78401. * Get the rotation matrix of the bone in local or world space
  78402. * @param space The space that the rotation should be in
  78403. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78404. * @returns The rotation matrix
  78405. */
  78406. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78407. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78408. var result = BABYLON.Matrix.Identity();
  78409. this.getRotationMatrixToRef(space, mesh, result);
  78410. return result;
  78411. };
  78412. /**
  78413. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78414. * @param space The space that the rotation should be in
  78415. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78416. * @param result The quaternion that the rotation should be copied to
  78417. */
  78418. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78419. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78420. if (space == BABYLON.Space.LOCAL) {
  78421. this.getLocalMatrix().getRotationMatrixToRef(result);
  78422. }
  78423. else {
  78424. var mat = Bone._tmpMats[0];
  78425. var amat = this.getAbsoluteTransform();
  78426. if (mesh) {
  78427. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78428. }
  78429. else {
  78430. mat.copyFrom(amat);
  78431. }
  78432. mat.m[0] *= this._scalingDeterminant;
  78433. mat.m[1] *= this._scalingDeterminant;
  78434. mat.m[2] *= this._scalingDeterminant;
  78435. mat.getRotationMatrixToRef(result);
  78436. }
  78437. };
  78438. /**
  78439. * Get the world position of a point that is in the local space of the bone
  78440. * @param position The local position
  78441. * @param mesh The mesh that this bone is attached to
  78442. * @returns The world position
  78443. */
  78444. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78445. if (mesh === void 0) { mesh = null; }
  78446. var result = BABYLON.Vector3.Zero();
  78447. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78448. return result;
  78449. };
  78450. /**
  78451. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78452. * @param position The local position
  78453. * @param mesh The mesh that this bone is attached to
  78454. * @param result The vector3 that the world position should be copied to
  78455. */
  78456. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78457. if (mesh === void 0) { mesh = null; }
  78458. var wm = null;
  78459. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78460. if (mesh) {
  78461. wm = mesh.getWorldMatrix();
  78462. }
  78463. this._skeleton.computeAbsoluteTransforms();
  78464. var tmat = Bone._tmpMats[0];
  78465. if (mesh && wm) {
  78466. tmat.copyFrom(this.getAbsoluteTransform());
  78467. tmat.multiplyToRef(wm, tmat);
  78468. }
  78469. else {
  78470. tmat = this.getAbsoluteTransform();
  78471. }
  78472. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78473. };
  78474. /**
  78475. * Get the local position of a point that is in world space
  78476. * @param position The world position
  78477. * @param mesh The mesh that this bone is attached to
  78478. * @returns The local position
  78479. */
  78480. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78481. if (mesh === void 0) { mesh = null; }
  78482. var result = BABYLON.Vector3.Zero();
  78483. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78484. return result;
  78485. };
  78486. /**
  78487. * Get the local position of a point that is in world space and copy it to the result param
  78488. * @param position The world position
  78489. * @param mesh The mesh that this bone is attached to
  78490. * @param result The vector3 that the local position should be copied to
  78491. */
  78492. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78493. if (mesh === void 0) { mesh = null; }
  78494. var wm = null;
  78495. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78496. if (mesh) {
  78497. wm = mesh.getWorldMatrix();
  78498. }
  78499. this._skeleton.computeAbsoluteTransforms();
  78500. var tmat = Bone._tmpMats[0];
  78501. tmat.copyFrom(this.getAbsoluteTransform());
  78502. if (mesh && wm) {
  78503. tmat.multiplyToRef(wm, tmat);
  78504. }
  78505. tmat.invert();
  78506. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78507. };
  78508. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78509. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78510. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78511. return Bone;
  78512. }(BABYLON.Node));
  78513. BABYLON.Bone = Bone;
  78514. })(BABYLON || (BABYLON = {}));
  78515. //# sourceMappingURL=babylon.bone.js.map
  78516. var BABYLON;
  78517. (function (BABYLON) {
  78518. /**
  78519. * Class used to apply inverse kinematics to bones
  78520. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78521. */
  78522. var BoneIKController = /** @class */ (function () {
  78523. /**
  78524. * Creates a new BoneIKController
  78525. * @param mesh defines the mesh to control
  78526. * @param bone defines the bone to control
  78527. * @param options defines options to set up the controller
  78528. */
  78529. function BoneIKController(mesh, bone, options) {
  78530. /**
  78531. * Gets or sets the target position
  78532. */
  78533. this.targetPosition = BABYLON.Vector3.Zero();
  78534. /**
  78535. * Gets or sets the pole target position
  78536. */
  78537. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78538. /**
  78539. * Gets or sets the pole target local offset
  78540. */
  78541. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78542. /**
  78543. * Gets or sets the pole angle
  78544. */
  78545. this.poleAngle = 0;
  78546. /**
  78547. * 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)
  78548. */
  78549. this.slerpAmount = 1;
  78550. this._bone1Quat = BABYLON.Quaternion.Identity();
  78551. this._bone1Mat = BABYLON.Matrix.Identity();
  78552. this._bone2Ang = Math.PI;
  78553. this._maxAngle = Math.PI;
  78554. this._rightHandedSystem = false;
  78555. this._bendAxis = BABYLON.Vector3.Right();
  78556. this._slerping = false;
  78557. this._adjustRoll = 0;
  78558. this._bone2 = bone;
  78559. this._bone1 = bone.getParent();
  78560. if (!this._bone1) {
  78561. return;
  78562. }
  78563. this.mesh = mesh;
  78564. var bonePos = bone.getPosition();
  78565. if (bone.getAbsoluteTransform().determinant() > 0) {
  78566. this._rightHandedSystem = true;
  78567. this._bendAxis.x = 0;
  78568. this._bendAxis.y = 0;
  78569. this._bendAxis.z = -1;
  78570. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78571. this._adjustRoll = Math.PI * .5;
  78572. this._bendAxis.z = 1;
  78573. }
  78574. }
  78575. if (this._bone1.length) {
  78576. var boneScale1 = this._bone1.getScale();
  78577. var boneScale2 = this._bone2.getScale();
  78578. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78579. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78580. }
  78581. else if (this._bone1.children[0]) {
  78582. mesh.computeWorldMatrix(true);
  78583. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78584. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78585. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78586. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78587. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78588. }
  78589. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78590. this.maxAngle = Math.PI;
  78591. if (options) {
  78592. if (options.targetMesh) {
  78593. this.targetMesh = options.targetMesh;
  78594. this.targetMesh.computeWorldMatrix(true);
  78595. }
  78596. if (options.poleTargetMesh) {
  78597. this.poleTargetMesh = options.poleTargetMesh;
  78598. this.poleTargetMesh.computeWorldMatrix(true);
  78599. }
  78600. else if (options.poleTargetBone) {
  78601. this.poleTargetBone = options.poleTargetBone;
  78602. }
  78603. else if (this._bone1.getParent()) {
  78604. this.poleTargetBone = this._bone1.getParent();
  78605. }
  78606. if (options.poleTargetLocalOffset) {
  78607. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78608. }
  78609. if (options.poleAngle) {
  78610. this.poleAngle = options.poleAngle;
  78611. }
  78612. if (options.bendAxis) {
  78613. this._bendAxis.copyFrom(options.bendAxis);
  78614. }
  78615. if (options.maxAngle) {
  78616. this.maxAngle = options.maxAngle;
  78617. }
  78618. if (options.slerpAmount) {
  78619. this.slerpAmount = options.slerpAmount;
  78620. }
  78621. }
  78622. }
  78623. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78624. /**
  78625. * Gets or sets maximum allowed angle
  78626. */
  78627. get: function () {
  78628. return this._maxAngle;
  78629. },
  78630. set: function (value) {
  78631. this._setMaxAngle(value);
  78632. },
  78633. enumerable: true,
  78634. configurable: true
  78635. });
  78636. BoneIKController.prototype._setMaxAngle = function (ang) {
  78637. if (ang < 0) {
  78638. ang = 0;
  78639. }
  78640. if (ang > Math.PI || ang == undefined) {
  78641. ang = Math.PI;
  78642. }
  78643. this._maxAngle = ang;
  78644. var a = this._bone1Length;
  78645. var b = this._bone2Length;
  78646. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78647. };
  78648. /**
  78649. * Force the controller to update the bones
  78650. */
  78651. BoneIKController.prototype.update = function () {
  78652. var bone1 = this._bone1;
  78653. if (!bone1) {
  78654. return;
  78655. }
  78656. var target = this.targetPosition;
  78657. var poleTarget = this.poleTargetPosition;
  78658. var mat1 = BoneIKController._tmpMats[0];
  78659. var mat2 = BoneIKController._tmpMats[1];
  78660. if (this.targetMesh) {
  78661. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78662. }
  78663. if (this.poleTargetBone) {
  78664. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78665. }
  78666. else if (this.poleTargetMesh) {
  78667. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78668. }
  78669. var bonePos = BoneIKController._tmpVecs[0];
  78670. var zaxis = BoneIKController._tmpVecs[1];
  78671. var xaxis = BoneIKController._tmpVecs[2];
  78672. var yaxis = BoneIKController._tmpVecs[3];
  78673. var upAxis = BoneIKController._tmpVecs[4];
  78674. var _tmpQuat = BoneIKController._tmpQuat;
  78675. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78676. poleTarget.subtractToRef(bonePos, upAxis);
  78677. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78678. upAxis.y = 1;
  78679. }
  78680. else {
  78681. upAxis.normalize();
  78682. }
  78683. target.subtractToRef(bonePos, yaxis);
  78684. yaxis.normalize();
  78685. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78686. zaxis.normalize();
  78687. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78688. xaxis.normalize();
  78689. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78690. var a = this._bone1Length;
  78691. var b = this._bone2Length;
  78692. var c = BABYLON.Vector3.Distance(bonePos, target);
  78693. if (this._maxReach > 0) {
  78694. c = Math.min(this._maxReach, c);
  78695. }
  78696. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78697. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78698. if (acosa > 1) {
  78699. acosa = 1;
  78700. }
  78701. if (acosb > 1) {
  78702. acosb = 1;
  78703. }
  78704. if (acosa < -1) {
  78705. acosa = -1;
  78706. }
  78707. if (acosb < -1) {
  78708. acosb = -1;
  78709. }
  78710. var angA = Math.acos(acosa);
  78711. var angB = Math.acos(acosb);
  78712. var angC = -angA - angB;
  78713. if (this._rightHandedSystem) {
  78714. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78715. mat2.multiplyToRef(mat1, mat1);
  78716. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78717. mat2.multiplyToRef(mat1, mat1);
  78718. }
  78719. else {
  78720. var _tmpVec = BoneIKController._tmpVecs[5];
  78721. _tmpVec.copyFrom(this._bendAxis);
  78722. _tmpVec.x *= -1;
  78723. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78724. mat2.multiplyToRef(mat1, mat1);
  78725. }
  78726. if (this.poleAngle) {
  78727. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78728. mat1.multiplyToRef(mat2, mat1);
  78729. }
  78730. if (this._bone1) {
  78731. if (this.slerpAmount < 1) {
  78732. if (!this._slerping) {
  78733. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78734. }
  78735. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78736. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78737. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78738. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78739. this._slerping = true;
  78740. }
  78741. else {
  78742. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78743. this._bone1Mat.copyFrom(mat1);
  78744. this._slerping = false;
  78745. }
  78746. }
  78747. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78748. this._bone2Ang = angC;
  78749. };
  78750. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78751. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78752. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78753. return BoneIKController;
  78754. }());
  78755. BABYLON.BoneIKController = BoneIKController;
  78756. })(BABYLON || (BABYLON = {}));
  78757. //# sourceMappingURL=babylon.boneIKController.js.map
  78758. var BABYLON;
  78759. (function (BABYLON) {
  78760. /**
  78761. * Class used to make a bone look toward a point in space
  78762. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78763. */
  78764. var BoneLookController = /** @class */ (function () {
  78765. /**
  78766. * Create a BoneLookController
  78767. * @param mesh the mesh that the bone belongs to
  78768. * @param bone the bone that will be looking to the target
  78769. * @param target the target Vector3 to look at
  78770. * @param settings optional settings:
  78771. * * maxYaw: the maximum angle the bone will yaw to
  78772. * * minYaw: the minimum angle the bone will yaw to
  78773. * * maxPitch: the maximum angle the bone will pitch to
  78774. * * minPitch: the minimum angle the bone will yaw to
  78775. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78776. * * upAxis: the up axis of the coordinate system
  78777. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78778. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78779. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78780. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78781. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78782. * * adjustRoll: used to make an adjustment to the roll of the bone
  78783. **/
  78784. function BoneLookController(mesh, bone, target, options) {
  78785. /**
  78786. * The up axis of the coordinate system that is used when the bone is rotated
  78787. */
  78788. this.upAxis = BABYLON.Vector3.Up();
  78789. /**
  78790. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78791. */
  78792. this.upAxisSpace = BABYLON.Space.LOCAL;
  78793. /**
  78794. * Used to make an adjustment to the yaw of the bone
  78795. */
  78796. this.adjustYaw = 0;
  78797. /**
  78798. * Used to make an adjustment to the pitch of the bone
  78799. */
  78800. this.adjustPitch = 0;
  78801. /**
  78802. * Used to make an adjustment to the roll of the bone
  78803. */
  78804. this.adjustRoll = 0;
  78805. /**
  78806. * 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)
  78807. */
  78808. this.slerpAmount = 1;
  78809. this._boneQuat = BABYLON.Quaternion.Identity();
  78810. this._slerping = false;
  78811. this._firstFrameSkipped = false;
  78812. this._fowardAxis = BABYLON.Vector3.Forward();
  78813. this.mesh = mesh;
  78814. this.bone = bone;
  78815. this.target = target;
  78816. if (options) {
  78817. if (options.adjustYaw) {
  78818. this.adjustYaw = options.adjustYaw;
  78819. }
  78820. if (options.adjustPitch) {
  78821. this.adjustPitch = options.adjustPitch;
  78822. }
  78823. if (options.adjustRoll) {
  78824. this.adjustRoll = options.adjustRoll;
  78825. }
  78826. if (options.maxYaw != null) {
  78827. this.maxYaw = options.maxYaw;
  78828. }
  78829. else {
  78830. this.maxYaw = Math.PI;
  78831. }
  78832. if (options.minYaw != null) {
  78833. this.minYaw = options.minYaw;
  78834. }
  78835. else {
  78836. this.minYaw = -Math.PI;
  78837. }
  78838. if (options.maxPitch != null) {
  78839. this.maxPitch = options.maxPitch;
  78840. }
  78841. else {
  78842. this.maxPitch = Math.PI;
  78843. }
  78844. if (options.minPitch != null) {
  78845. this.minPitch = options.minPitch;
  78846. }
  78847. else {
  78848. this.minPitch = -Math.PI;
  78849. }
  78850. if (options.slerpAmount != null) {
  78851. this.slerpAmount = options.slerpAmount;
  78852. }
  78853. if (options.upAxis != null) {
  78854. this.upAxis = options.upAxis;
  78855. }
  78856. if (options.upAxisSpace != null) {
  78857. this.upAxisSpace = options.upAxisSpace;
  78858. }
  78859. if (options.yawAxis != null || options.pitchAxis != null) {
  78860. var newYawAxis = BABYLON.Axis.Y;
  78861. var newPitchAxis = BABYLON.Axis.X;
  78862. if (options.yawAxis != null) {
  78863. newYawAxis = options.yawAxis.clone();
  78864. newYawAxis.normalize();
  78865. }
  78866. if (options.pitchAxis != null) {
  78867. newPitchAxis = options.pitchAxis.clone();
  78868. newPitchAxis.normalize();
  78869. }
  78870. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78871. this._transformYawPitch = BABYLON.Matrix.Identity();
  78872. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78873. this._transformYawPitchInv = this._transformYawPitch.clone();
  78874. this._transformYawPitch.invert();
  78875. }
  78876. }
  78877. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78878. this.upAxisSpace = BABYLON.Space.LOCAL;
  78879. }
  78880. }
  78881. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78882. /**
  78883. * Gets or sets the minimum yaw angle that the bone can look to
  78884. */
  78885. get: function () {
  78886. return this._minYaw;
  78887. },
  78888. set: function (value) {
  78889. this._minYaw = value;
  78890. this._minYawSin = Math.sin(value);
  78891. this._minYawCos = Math.cos(value);
  78892. if (this._maxYaw != null) {
  78893. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78894. this._yawRange = this._maxYaw - this._minYaw;
  78895. }
  78896. },
  78897. enumerable: true,
  78898. configurable: true
  78899. });
  78900. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78901. /**
  78902. * Gets or sets the maximum yaw angle that the bone can look to
  78903. */
  78904. get: function () {
  78905. return this._maxYaw;
  78906. },
  78907. set: function (value) {
  78908. this._maxYaw = value;
  78909. this._maxYawSin = Math.sin(value);
  78910. this._maxYawCos = Math.cos(value);
  78911. if (this._minYaw != null) {
  78912. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78913. this._yawRange = this._maxYaw - this._minYaw;
  78914. }
  78915. },
  78916. enumerable: true,
  78917. configurable: true
  78918. });
  78919. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78920. /**
  78921. * Gets or sets the minimum pitch angle that the bone can look to
  78922. */
  78923. get: function () {
  78924. return this._minPitch;
  78925. },
  78926. set: function (value) {
  78927. this._minPitch = value;
  78928. this._minPitchTan = Math.tan(value);
  78929. },
  78930. enumerable: true,
  78931. configurable: true
  78932. });
  78933. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78934. /**
  78935. * Gets or sets the maximum pitch angle that the bone can look to
  78936. */
  78937. get: function () {
  78938. return this._maxPitch;
  78939. },
  78940. set: function (value) {
  78941. this._maxPitch = value;
  78942. this._maxPitchTan = Math.tan(value);
  78943. },
  78944. enumerable: true,
  78945. configurable: true
  78946. });
  78947. /**
  78948. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78949. */
  78950. BoneLookController.prototype.update = function () {
  78951. //skip the first frame when slerping so that the mesh rotation is correct
  78952. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78953. this._firstFrameSkipped = true;
  78954. return;
  78955. }
  78956. var bone = this.bone;
  78957. var bonePos = BoneLookController._tmpVecs[0];
  78958. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78959. var target = this.target;
  78960. var _tmpMat1 = BoneLookController._tmpMats[0];
  78961. var _tmpMat2 = BoneLookController._tmpMats[1];
  78962. var mesh = this.mesh;
  78963. var parentBone = bone.getParent();
  78964. var upAxis = BoneLookController._tmpVecs[1];
  78965. upAxis.copyFrom(this.upAxis);
  78966. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78967. if (this._transformYawPitch) {
  78968. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78969. }
  78970. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78971. }
  78972. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78973. mesh.getDirectionToRef(upAxis, upAxis);
  78974. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78975. upAxis.normalize();
  78976. }
  78977. }
  78978. var checkYaw = false;
  78979. var checkPitch = false;
  78980. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78981. checkYaw = true;
  78982. }
  78983. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78984. checkPitch = true;
  78985. }
  78986. if (checkYaw || checkPitch) {
  78987. var spaceMat = BoneLookController._tmpMats[2];
  78988. var spaceMatInv = BoneLookController._tmpMats[3];
  78989. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78990. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78991. }
  78992. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78993. spaceMat.copyFrom(mesh.getWorldMatrix());
  78994. }
  78995. else {
  78996. var forwardAxis = BoneLookController._tmpVecs[2];
  78997. forwardAxis.copyFrom(this._fowardAxis);
  78998. if (this._transformYawPitch) {
  78999. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  79000. }
  79001. if (parentBone) {
  79002. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  79003. }
  79004. else {
  79005. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  79006. }
  79007. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  79008. rightAxis.normalize();
  79009. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  79010. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  79011. }
  79012. spaceMat.invertToRef(spaceMatInv);
  79013. var xzlen = null;
  79014. if (checkPitch) {
  79015. var localTarget = BoneLookController._tmpVecs[3];
  79016. target.subtractToRef(bonePos, localTarget);
  79017. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79018. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79019. var pitch = Math.atan2(localTarget.y, xzlen);
  79020. var newPitch = pitch;
  79021. if (pitch > this._maxPitch) {
  79022. localTarget.y = this._maxPitchTan * xzlen;
  79023. newPitch = this._maxPitch;
  79024. }
  79025. else if (pitch < this._minPitch) {
  79026. localTarget.y = this._minPitchTan * xzlen;
  79027. newPitch = this._minPitch;
  79028. }
  79029. if (pitch != newPitch) {
  79030. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79031. localTarget.addInPlace(bonePos);
  79032. target = localTarget;
  79033. }
  79034. }
  79035. if (checkYaw) {
  79036. var localTarget = BoneLookController._tmpVecs[4];
  79037. target.subtractToRef(bonePos, localTarget);
  79038. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79039. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79040. var newYaw = yaw;
  79041. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79042. if (xzlen == null) {
  79043. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79044. }
  79045. if (this._yawRange > Math.PI) {
  79046. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79047. localTarget.z = this._maxYawCos * xzlen;
  79048. localTarget.x = this._maxYawSin * xzlen;
  79049. newYaw = this._maxYaw;
  79050. }
  79051. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79052. localTarget.z = this._minYawCos * xzlen;
  79053. localTarget.x = this._minYawSin * xzlen;
  79054. newYaw = this._minYaw;
  79055. }
  79056. }
  79057. else {
  79058. if (yaw > this._maxYaw) {
  79059. localTarget.z = this._maxYawCos * xzlen;
  79060. localTarget.x = this._maxYawSin * xzlen;
  79061. newYaw = this._maxYaw;
  79062. }
  79063. else if (yaw < this._minYaw) {
  79064. localTarget.z = this._minYawCos * xzlen;
  79065. localTarget.x = this._minYawSin * xzlen;
  79066. newYaw = this._minYaw;
  79067. }
  79068. }
  79069. }
  79070. if (this._slerping && this._yawRange > Math.PI) {
  79071. //are we going to be crossing into the min/max region?
  79072. var boneFwd = BoneLookController._tmpVecs[8];
  79073. boneFwd.copyFrom(BABYLON.Axis.Z);
  79074. if (this._transformYawPitch) {
  79075. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79076. }
  79077. var boneRotMat = BoneLookController._tmpMats[4];
  79078. this._boneQuat.toRotationMatrix(boneRotMat);
  79079. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79080. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79081. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79082. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79083. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79084. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79085. if (angBtwTar > angBtwMidYaw) {
  79086. if (xzlen == null) {
  79087. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79088. }
  79089. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79090. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79091. if (angBtwMin < angBtwMax) {
  79092. newYaw = boneYaw + Math.PI * .75;
  79093. localTarget.z = Math.cos(newYaw) * xzlen;
  79094. localTarget.x = Math.sin(newYaw) * xzlen;
  79095. }
  79096. else {
  79097. newYaw = boneYaw - Math.PI * .75;
  79098. localTarget.z = Math.cos(newYaw) * xzlen;
  79099. localTarget.x = Math.sin(newYaw) * xzlen;
  79100. }
  79101. }
  79102. }
  79103. if (yaw != newYaw) {
  79104. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79105. localTarget.addInPlace(bonePos);
  79106. target = localTarget;
  79107. }
  79108. }
  79109. }
  79110. var zaxis = BoneLookController._tmpVecs[5];
  79111. var xaxis = BoneLookController._tmpVecs[6];
  79112. var yaxis = BoneLookController._tmpVecs[7];
  79113. var _tmpQuat = BoneLookController._tmpQuat;
  79114. target.subtractToRef(bonePos, zaxis);
  79115. zaxis.normalize();
  79116. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79117. xaxis.normalize();
  79118. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79119. yaxis.normalize();
  79120. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79121. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79122. return;
  79123. }
  79124. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79125. return;
  79126. }
  79127. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79128. return;
  79129. }
  79130. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79131. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79132. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79133. }
  79134. if (this.slerpAmount < 1) {
  79135. if (!this._slerping) {
  79136. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79137. }
  79138. if (this._transformYawPitch) {
  79139. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79140. }
  79141. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79142. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79143. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79144. this._slerping = true;
  79145. }
  79146. else {
  79147. if (this._transformYawPitch) {
  79148. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79149. }
  79150. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79151. this._slerping = false;
  79152. }
  79153. };
  79154. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79155. var angDiff = ang2 - ang1;
  79156. angDiff %= Math.PI * 2;
  79157. if (angDiff > Math.PI) {
  79158. angDiff -= Math.PI * 2;
  79159. }
  79160. else if (angDiff < -Math.PI) {
  79161. angDiff += Math.PI * 2;
  79162. }
  79163. return angDiff;
  79164. };
  79165. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79166. ang1 %= (2 * Math.PI);
  79167. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79168. ang2 %= (2 * Math.PI);
  79169. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79170. var ab = 0;
  79171. if (ang1 < ang2) {
  79172. ab = ang2 - ang1;
  79173. }
  79174. else {
  79175. ab = ang1 - ang2;
  79176. }
  79177. if (ab > Math.PI) {
  79178. ab = Math.PI * 2 - ab;
  79179. }
  79180. return ab;
  79181. };
  79182. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79183. ang %= (2 * Math.PI);
  79184. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79185. ang1 %= (2 * Math.PI);
  79186. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79187. ang2 %= (2 * Math.PI);
  79188. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79189. if (ang1 < ang2) {
  79190. if (ang > ang1 && ang < ang2) {
  79191. return true;
  79192. }
  79193. }
  79194. else {
  79195. if (ang > ang2 && ang < ang1) {
  79196. return true;
  79197. }
  79198. }
  79199. return false;
  79200. };
  79201. 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()];
  79202. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79203. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79204. return BoneLookController;
  79205. }());
  79206. BABYLON.BoneLookController = BoneLookController;
  79207. })(BABYLON || (BABYLON = {}));
  79208. //# sourceMappingURL=babylon.boneLookController.js.map
  79209. var BABYLON;
  79210. (function (BABYLON) {
  79211. /**
  79212. * Class used to handle skinning animations
  79213. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79214. */
  79215. var Skeleton = /** @class */ (function () {
  79216. /**
  79217. * Creates a new skeleton
  79218. * @param name defines the skeleton name
  79219. * @param id defines the skeleton Id
  79220. * @param scene defines the hosting scene
  79221. */
  79222. function Skeleton(
  79223. /** defines the skeleton name */
  79224. name,
  79225. /** defines the skeleton Id */
  79226. id, scene) {
  79227. this.name = name;
  79228. this.id = id;
  79229. /**
  79230. * Gets the list of child bones
  79231. */
  79232. this.bones = new Array();
  79233. /**
  79234. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79235. */
  79236. this.needInitialSkinMatrix = false;
  79237. this._isDirty = true;
  79238. this._meshesWithPoseMatrix = new Array();
  79239. this._identity = BABYLON.Matrix.Identity();
  79240. this._ranges = {};
  79241. this._lastAbsoluteTransformsUpdateId = -1;
  79242. /**
  79243. * Specifies if the skeleton should be serialized
  79244. */
  79245. this.doNotSerialize = false;
  79246. this._animationPropertiesOverride = null;
  79247. // Events
  79248. /**
  79249. * An observable triggered before computing the skeleton's matrices
  79250. */
  79251. this.onBeforeComputeObservable = new BABYLON.Observable();
  79252. this.bones = [];
  79253. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79254. scene.skeletons.push(this);
  79255. //make sure it will recalculate the matrix next time prepare is called.
  79256. this._isDirty = true;
  79257. }
  79258. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79259. /**
  79260. * Gets or sets the animation properties override
  79261. */
  79262. get: function () {
  79263. if (!this._animationPropertiesOverride) {
  79264. return this._scene.animationPropertiesOverride;
  79265. }
  79266. return this._animationPropertiesOverride;
  79267. },
  79268. set: function (value) {
  79269. this._animationPropertiesOverride = value;
  79270. },
  79271. enumerable: true,
  79272. configurable: true
  79273. });
  79274. // Members
  79275. /**
  79276. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79277. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79278. * @returns a Float32Array containing matrices data
  79279. */
  79280. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79281. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79282. return mesh._bonesTransformMatrices;
  79283. }
  79284. if (!this._transformMatrices) {
  79285. this.prepare();
  79286. }
  79287. return this._transformMatrices;
  79288. };
  79289. /**
  79290. * Gets the current hosting scene
  79291. * @returns a scene object
  79292. */
  79293. Skeleton.prototype.getScene = function () {
  79294. return this._scene;
  79295. };
  79296. // Methods
  79297. /**
  79298. * Gets a string representing the current skeleton data
  79299. * @param fullDetails defines a boolean indicating if we want a verbose version
  79300. * @returns a string representing the current skeleton data
  79301. */
  79302. Skeleton.prototype.toString = function (fullDetails) {
  79303. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79304. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79305. if (fullDetails) {
  79306. ret += ", Ranges: {";
  79307. var first = true;
  79308. for (var name_1 in this._ranges) {
  79309. if (first) {
  79310. ret += ", ";
  79311. first = false;
  79312. }
  79313. ret += name_1;
  79314. }
  79315. ret += "}";
  79316. }
  79317. return ret;
  79318. };
  79319. /**
  79320. * Get bone's index searching by name
  79321. * @param name defines bone's name to search for
  79322. * @return the indice of the bone. Returns -1 if not found
  79323. */
  79324. Skeleton.prototype.getBoneIndexByName = function (name) {
  79325. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79326. if (this.bones[boneIndex].name === name) {
  79327. return boneIndex;
  79328. }
  79329. }
  79330. return -1;
  79331. };
  79332. /**
  79333. * Creater a new animation range
  79334. * @param name defines the name of the range
  79335. * @param from defines the start key
  79336. * @param to defines the end key
  79337. */
  79338. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79339. // check name not already in use
  79340. if (!this._ranges[name]) {
  79341. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79342. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79343. if (this.bones[i].animations[0]) {
  79344. this.bones[i].animations[0].createRange(name, from, to);
  79345. }
  79346. }
  79347. }
  79348. };
  79349. /**
  79350. * Delete a specific animation range
  79351. * @param name defines the name of the range
  79352. * @param deleteFrames defines if frames must be removed as well
  79353. */
  79354. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79355. if (deleteFrames === void 0) { deleteFrames = true; }
  79356. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79357. if (this.bones[i].animations[0]) {
  79358. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79359. }
  79360. }
  79361. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79362. };
  79363. /**
  79364. * Gets a specific animation range
  79365. * @param name defines the name of the range to look for
  79366. * @returns the requested animation range or null if not found
  79367. */
  79368. Skeleton.prototype.getAnimationRange = function (name) {
  79369. return this._ranges[name];
  79370. };
  79371. /**
  79372. * Gets the list of all animation ranges defined on this skeleton
  79373. * @returns an array
  79374. */
  79375. Skeleton.prototype.getAnimationRanges = function () {
  79376. var animationRanges = [];
  79377. var name;
  79378. var i = 0;
  79379. for (name in this._ranges) {
  79380. animationRanges[i] = this._ranges[name];
  79381. i++;
  79382. }
  79383. return animationRanges;
  79384. };
  79385. /**
  79386. * Copy animation range from a source skeleton.
  79387. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79388. * @param source defines the source skeleton
  79389. * @param name defines the name of the range to copy
  79390. * @param rescaleAsRequired defines if rescaling must be applied if required
  79391. * @returns true if operation was successful
  79392. */
  79393. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79394. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79395. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79396. return false;
  79397. }
  79398. var ret = true;
  79399. var frameOffset = this._getHighestAnimationFrame() + 1;
  79400. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79401. var boneDict = {};
  79402. var sourceBones = source.bones;
  79403. var nBones;
  79404. var i;
  79405. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79406. boneDict[sourceBones[i].name] = sourceBones[i];
  79407. }
  79408. if (this.bones.length !== sourceBones.length) {
  79409. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79410. ret = false;
  79411. }
  79412. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79413. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79414. var boneName = this.bones[i].name;
  79415. var sourceBone = boneDict[boneName];
  79416. if (sourceBone) {
  79417. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79418. }
  79419. else {
  79420. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79421. ret = false;
  79422. }
  79423. }
  79424. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79425. var range = source.getAnimationRange(name);
  79426. if (range) {
  79427. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79428. }
  79429. return ret;
  79430. };
  79431. /**
  79432. * Forces the skeleton to go to rest pose
  79433. */
  79434. Skeleton.prototype.returnToRest = function () {
  79435. for (var index = 0; index < this.bones.length; index++) {
  79436. this.bones[index].returnToRest();
  79437. }
  79438. };
  79439. Skeleton.prototype._getHighestAnimationFrame = function () {
  79440. var ret = 0;
  79441. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79442. if (this.bones[i].animations[0]) {
  79443. var highest = this.bones[i].animations[0].getHighestFrame();
  79444. if (ret < highest) {
  79445. ret = highest;
  79446. }
  79447. }
  79448. }
  79449. return ret;
  79450. };
  79451. /**
  79452. * Begin a specific animation range
  79453. * @param name defines the name of the range to start
  79454. * @param loop defines if looping must be turned on (false by default)
  79455. * @param speedRatio defines the speed ratio to apply (1 by default)
  79456. * @param onAnimationEnd defines a callback which will be called when animation will end
  79457. * @returns a new animatable
  79458. */
  79459. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79460. var range = this.getAnimationRange(name);
  79461. if (!range) {
  79462. return null;
  79463. }
  79464. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79465. };
  79466. /** @hidden */
  79467. Skeleton.prototype._markAsDirty = function () {
  79468. this._isDirty = true;
  79469. };
  79470. /** @hidden */
  79471. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79472. this._meshesWithPoseMatrix.push(mesh);
  79473. };
  79474. /** @hidden */
  79475. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79476. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79477. if (index > -1) {
  79478. this._meshesWithPoseMatrix.splice(index, 1);
  79479. }
  79480. };
  79481. /** @hidden */
  79482. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79483. this.onBeforeComputeObservable.notifyObservers(this);
  79484. for (var index = 0; index < this.bones.length; index++) {
  79485. var bone = this.bones[index];
  79486. var parentBone = bone.getParent();
  79487. if (parentBone) {
  79488. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79489. }
  79490. else {
  79491. if (initialSkinMatrix) {
  79492. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79493. }
  79494. else {
  79495. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79496. }
  79497. }
  79498. if (bone._index !== -1) {
  79499. var mappedIndex = bone._index === null ? index : bone._index;
  79500. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79501. }
  79502. }
  79503. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79504. };
  79505. /**
  79506. * Build all resources required to render a skeleton
  79507. */
  79508. Skeleton.prototype.prepare = function () {
  79509. if (!this._isDirty) {
  79510. return;
  79511. }
  79512. if (this.needInitialSkinMatrix) {
  79513. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79514. var mesh = this._meshesWithPoseMatrix[index];
  79515. var poseMatrix = mesh.getPoseMatrix();
  79516. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79517. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79518. }
  79519. if (this._synchronizedWithMesh !== mesh) {
  79520. this._synchronizedWithMesh = mesh;
  79521. // Prepare bones
  79522. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79523. var bone = this.bones[boneIndex];
  79524. if (!bone.getParent()) {
  79525. var matrix = bone.getBaseMatrix();
  79526. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79527. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79528. }
  79529. }
  79530. }
  79531. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79532. }
  79533. }
  79534. else {
  79535. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79536. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79537. }
  79538. this._computeTransformMatrices(this._transformMatrices, null);
  79539. }
  79540. this._isDirty = false;
  79541. this._scene._activeBones.addCount(this.bones.length, false);
  79542. };
  79543. /**
  79544. * Gets the list of animatables currently running for this skeleton
  79545. * @returns an array of animatables
  79546. */
  79547. Skeleton.prototype.getAnimatables = function () {
  79548. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79549. this._animatables = [];
  79550. for (var index = 0; index < this.bones.length; index++) {
  79551. this._animatables.push(this.bones[index]);
  79552. }
  79553. }
  79554. return this._animatables;
  79555. };
  79556. /**
  79557. * Clone the current skeleton
  79558. * @param name defines the name of the new skeleton
  79559. * @param id defines the id of the enw skeleton
  79560. * @returns the new skeleton
  79561. */
  79562. Skeleton.prototype.clone = function (name, id) {
  79563. var result = new Skeleton(name, id || name, this._scene);
  79564. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79565. for (var index = 0; index < this.bones.length; index++) {
  79566. var source = this.bones[index];
  79567. var parentBone = null;
  79568. var parent_1 = source.getParent();
  79569. if (parent_1) {
  79570. var parentIndex = this.bones.indexOf(parent_1);
  79571. parentBone = result.bones[parentIndex];
  79572. }
  79573. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79574. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79575. }
  79576. if (this._ranges) {
  79577. result._ranges = {};
  79578. for (var rangeName in this._ranges) {
  79579. var range = this._ranges[rangeName];
  79580. if (range) {
  79581. result._ranges[rangeName] = range.clone();
  79582. }
  79583. }
  79584. }
  79585. this._isDirty = true;
  79586. return result;
  79587. };
  79588. /**
  79589. * Enable animation blending for this skeleton
  79590. * @param blendingSpeed defines the blending speed to apply
  79591. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79592. */
  79593. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79594. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79595. this.bones.forEach(function (bone) {
  79596. bone.animations.forEach(function (animation) {
  79597. animation.enableBlending = true;
  79598. animation.blendingSpeed = blendingSpeed;
  79599. });
  79600. });
  79601. };
  79602. /**
  79603. * Releases all resources associated with the current skeleton
  79604. */
  79605. Skeleton.prototype.dispose = function () {
  79606. this._meshesWithPoseMatrix = [];
  79607. // Animations
  79608. this.getScene().stopAnimation(this);
  79609. // Remove from scene
  79610. this.getScene().removeSkeleton(this);
  79611. };
  79612. /**
  79613. * Serialize the skeleton in a JSON object
  79614. * @returns a JSON object
  79615. */
  79616. Skeleton.prototype.serialize = function () {
  79617. var serializationObject = {};
  79618. serializationObject.name = this.name;
  79619. serializationObject.id = this.id;
  79620. if (this.dimensionsAtRest) {
  79621. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79622. }
  79623. serializationObject.bones = [];
  79624. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79625. for (var index = 0; index < this.bones.length; index++) {
  79626. var bone = this.bones[index];
  79627. var parent_2 = bone.getParent();
  79628. var serializedBone = {
  79629. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79630. name: bone.name,
  79631. matrix: bone.getBaseMatrix().toArray(),
  79632. rest: bone.getRestPose().toArray()
  79633. };
  79634. serializationObject.bones.push(serializedBone);
  79635. if (bone.length) {
  79636. serializedBone.length = bone.length;
  79637. }
  79638. if (bone.metadata) {
  79639. serializedBone.metadata = bone.metadata;
  79640. }
  79641. if (bone.animations && bone.animations.length > 0) {
  79642. serializedBone.animation = bone.animations[0].serialize();
  79643. }
  79644. serializationObject.ranges = [];
  79645. for (var name in this._ranges) {
  79646. var source = this._ranges[name];
  79647. if (!source) {
  79648. continue;
  79649. }
  79650. var range = {};
  79651. range.name = name;
  79652. range.from = source.from;
  79653. range.to = source.to;
  79654. serializationObject.ranges.push(range);
  79655. }
  79656. }
  79657. return serializationObject;
  79658. };
  79659. /**
  79660. * Creates a new skeleton from serialized data
  79661. * @param parsedSkeleton defines the serialized data
  79662. * @param scene defines the hosting scene
  79663. * @returns a new skeleton
  79664. */
  79665. Skeleton.Parse = function (parsedSkeleton, scene) {
  79666. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79667. if (parsedSkeleton.dimensionsAtRest) {
  79668. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79669. }
  79670. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79671. var index;
  79672. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79673. var parsedBone = parsedSkeleton.bones[index];
  79674. var parentBone = null;
  79675. if (parsedBone.parentBoneIndex > -1) {
  79676. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79677. }
  79678. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79679. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79680. if (parsedBone.length) {
  79681. bone.length = parsedBone.length;
  79682. }
  79683. if (parsedBone.metadata) {
  79684. bone.metadata = parsedBone.metadata;
  79685. }
  79686. if (parsedBone.animation) {
  79687. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79688. }
  79689. }
  79690. // placed after bones, so createAnimationRange can cascade down
  79691. if (parsedSkeleton.ranges) {
  79692. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79693. var data = parsedSkeleton.ranges[index];
  79694. skeleton.createAnimationRange(data.name, data.from, data.to);
  79695. }
  79696. }
  79697. return skeleton;
  79698. };
  79699. /**
  79700. * Compute all node absolute transforms
  79701. * @param forceUpdate defines if computation must be done even if cache is up to date
  79702. */
  79703. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79704. if (forceUpdate === void 0) { forceUpdate = false; }
  79705. var renderId = this._scene.getRenderId();
  79706. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79707. this.bones[0].computeAbsoluteTransforms();
  79708. this._lastAbsoluteTransformsUpdateId = renderId;
  79709. }
  79710. };
  79711. /**
  79712. * Gets the root pose matrix
  79713. * @returns a matrix
  79714. */
  79715. Skeleton.prototype.getPoseMatrix = function () {
  79716. var poseMatrix = null;
  79717. if (this._meshesWithPoseMatrix.length > 0) {
  79718. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79719. }
  79720. return poseMatrix;
  79721. };
  79722. /**
  79723. * Sorts bones per internal index
  79724. */
  79725. Skeleton.prototype.sortBones = function () {
  79726. var bones = new Array();
  79727. var visited = new Array(this.bones.length);
  79728. for (var index = 0; index < this.bones.length; index++) {
  79729. this._sortBones(index, bones, visited);
  79730. }
  79731. this.bones = bones;
  79732. };
  79733. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79734. if (visited[index]) {
  79735. return;
  79736. }
  79737. visited[index] = true;
  79738. var bone = this.bones[index];
  79739. if (bone._index === undefined) {
  79740. bone._index = index;
  79741. }
  79742. var parentBone = bone.getParent();
  79743. if (parentBone) {
  79744. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79745. }
  79746. bones.push(bone);
  79747. };
  79748. return Skeleton;
  79749. }());
  79750. BABYLON.Skeleton = Skeleton;
  79751. })(BABYLON || (BABYLON = {}));
  79752. //# sourceMappingURL=babylon.skeleton.js.map
  79753. var BABYLON;
  79754. (function (BABYLON) {
  79755. var SphericalPolynomial = /** @class */ (function () {
  79756. function SphericalPolynomial() {
  79757. this.x = BABYLON.Vector3.Zero();
  79758. this.y = BABYLON.Vector3.Zero();
  79759. this.z = BABYLON.Vector3.Zero();
  79760. this.xx = BABYLON.Vector3.Zero();
  79761. this.yy = BABYLON.Vector3.Zero();
  79762. this.zz = BABYLON.Vector3.Zero();
  79763. this.xy = BABYLON.Vector3.Zero();
  79764. this.yz = BABYLON.Vector3.Zero();
  79765. this.zx = BABYLON.Vector3.Zero();
  79766. }
  79767. SphericalPolynomial.prototype.addAmbient = function (color) {
  79768. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79769. this.xx = this.xx.add(colorVector);
  79770. this.yy = this.yy.add(colorVector);
  79771. this.zz = this.zz.add(colorVector);
  79772. };
  79773. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79774. var result = new SphericalPolynomial();
  79775. result.x = harmonics.L11.scale(1.02333);
  79776. result.y = harmonics.L1_1.scale(1.02333);
  79777. result.z = harmonics.L10.scale(1.02333);
  79778. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79779. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79780. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79781. result.yz = harmonics.L2_1.scale(0.858086);
  79782. result.zx = harmonics.L21.scale(0.858086);
  79783. result.xy = harmonics.L2_2.scale(0.858086);
  79784. result.scale(1.0 / Math.PI);
  79785. return result;
  79786. };
  79787. SphericalPolynomial.prototype.scale = function (scale) {
  79788. this.x = this.x.scale(scale);
  79789. this.y = this.y.scale(scale);
  79790. this.z = this.z.scale(scale);
  79791. this.xx = this.xx.scale(scale);
  79792. this.yy = this.yy.scale(scale);
  79793. this.zz = this.zz.scale(scale);
  79794. this.yz = this.yz.scale(scale);
  79795. this.zx = this.zx.scale(scale);
  79796. this.xy = this.xy.scale(scale);
  79797. };
  79798. return SphericalPolynomial;
  79799. }());
  79800. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79801. var SphericalHarmonics = /** @class */ (function () {
  79802. function SphericalHarmonics() {
  79803. this.L00 = BABYLON.Vector3.Zero();
  79804. this.L1_1 = BABYLON.Vector3.Zero();
  79805. this.L10 = BABYLON.Vector3.Zero();
  79806. this.L11 = BABYLON.Vector3.Zero();
  79807. this.L2_2 = BABYLON.Vector3.Zero();
  79808. this.L2_1 = BABYLON.Vector3.Zero();
  79809. this.L20 = BABYLON.Vector3.Zero();
  79810. this.L21 = BABYLON.Vector3.Zero();
  79811. this.L22 = BABYLON.Vector3.Zero();
  79812. }
  79813. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79814. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79815. var c = colorVector.scale(deltaSolidAngle);
  79816. this.L00 = this.L00.add(c.scale(0.282095));
  79817. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79818. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79819. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79820. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79821. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79822. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79823. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79824. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79825. };
  79826. SphericalHarmonics.prototype.scale = function (scale) {
  79827. this.L00 = this.L00.scale(scale);
  79828. this.L1_1 = this.L1_1.scale(scale);
  79829. this.L10 = this.L10.scale(scale);
  79830. this.L11 = this.L11.scale(scale);
  79831. this.L2_2 = this.L2_2.scale(scale);
  79832. this.L2_1 = this.L2_1.scale(scale);
  79833. this.L20 = this.L20.scale(scale);
  79834. this.L21 = this.L21.scale(scale);
  79835. this.L22 = this.L22.scale(scale);
  79836. };
  79837. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79838. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79839. //
  79840. // E_lm = A_l * L_lm
  79841. //
  79842. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79843. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79844. // the scaling factors are given in equation 9.
  79845. // Constant (Band 0)
  79846. this.L00 = this.L00.scale(3.141593);
  79847. // Linear (Band 1)
  79848. this.L1_1 = this.L1_1.scale(2.094395);
  79849. this.L10 = this.L10.scale(2.094395);
  79850. this.L11 = this.L11.scale(2.094395);
  79851. // Quadratic (Band 2)
  79852. this.L2_2 = this.L2_2.scale(0.785398);
  79853. this.L2_1 = this.L2_1.scale(0.785398);
  79854. this.L20 = this.L20.scale(0.785398);
  79855. this.L21 = this.L21.scale(0.785398);
  79856. this.L22 = this.L22.scale(0.785398);
  79857. };
  79858. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79859. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79860. // L = (1/pi) * E * rho
  79861. //
  79862. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79863. this.scale(1.0 / Math.PI);
  79864. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79865. // (The pixel shader must apply albedo after texture fetches, etc).
  79866. };
  79867. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79868. var result = new SphericalHarmonics();
  79869. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79870. result.L1_1 = polynomial.y.scale(0.977204);
  79871. result.L10 = polynomial.z.scale(0.977204);
  79872. result.L11 = polynomial.x.scale(0.977204);
  79873. result.L2_2 = polynomial.xy.scale(1.16538);
  79874. result.L2_1 = polynomial.yz.scale(1.16538);
  79875. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79876. result.L21 = polynomial.zx.scale(1.16538);
  79877. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79878. result.scale(Math.PI);
  79879. return result;
  79880. };
  79881. return SphericalHarmonics;
  79882. }());
  79883. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79884. })(BABYLON || (BABYLON = {}));
  79885. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79886. var BABYLON;
  79887. (function (BABYLON) {
  79888. var FileFaceOrientation = /** @class */ (function () {
  79889. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79890. this.name = name;
  79891. this.worldAxisForNormal = worldAxisForNormal;
  79892. this.worldAxisForFileX = worldAxisForFileX;
  79893. this.worldAxisForFileY = worldAxisForFileY;
  79894. }
  79895. return FileFaceOrientation;
  79896. }());
  79897. ;
  79898. /**
  79899. * Helper class dealing with the extraction of spherical polynomial dataArray
  79900. * from a cube map.
  79901. */
  79902. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79903. function CubeMapToSphericalPolynomialTools() {
  79904. }
  79905. /**
  79906. * Converts a texture to the according Spherical Polynomial data.
  79907. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79908. *
  79909. * @param texture The texture to extract the information from.
  79910. * @return The Spherical Polynomial data.
  79911. */
  79912. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79913. if (!texture.isCube) {
  79914. // Only supports cube Textures currently.
  79915. return null;
  79916. }
  79917. var size = texture.getSize().width;
  79918. var right = texture.readPixels(0);
  79919. var left = texture.readPixels(1);
  79920. var up;
  79921. var down;
  79922. if (texture.isRenderTarget) {
  79923. up = texture.readPixels(3);
  79924. down = texture.readPixels(2);
  79925. }
  79926. else {
  79927. up = texture.readPixels(2);
  79928. down = texture.readPixels(3);
  79929. }
  79930. var front = texture.readPixels(4);
  79931. var back = texture.readPixels(5);
  79932. var gammaSpace = texture.gammaSpace;
  79933. // Always read as RGBA.
  79934. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79935. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79936. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79937. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79938. }
  79939. var cubeInfo = {
  79940. size: size,
  79941. right: right,
  79942. left: left,
  79943. up: up,
  79944. down: down,
  79945. front: front,
  79946. back: back,
  79947. format: format,
  79948. type: type,
  79949. gammaSpace: gammaSpace,
  79950. };
  79951. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79952. };
  79953. /**
  79954. * Converts a cubemap to the according Spherical Polynomial data.
  79955. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79956. *
  79957. * @param cubeInfo The Cube map to extract the information from.
  79958. * @return The Spherical Polynomial data.
  79959. */
  79960. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79961. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79962. var totalSolidAngle = 0.0;
  79963. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79964. var du = 2.0 / cubeInfo.size;
  79965. var dv = du;
  79966. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79967. var minUV = du * 0.5 - 1.0;
  79968. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79969. var fileFace = this.FileFaces[faceIndex];
  79970. var dataArray = cubeInfo[fileFace.name];
  79971. var v = minUV;
  79972. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79973. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79974. // Because SP is still linear, so summation is fine in that basis.
  79975. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79976. for (var y = 0; y < cubeInfo.size; y++) {
  79977. var u = minUV;
  79978. for (var x = 0; x < cubeInfo.size; x++) {
  79979. // World direction (not normalised)
  79980. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79981. worldDirection.normalize();
  79982. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79983. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79984. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79985. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79986. // Handle Integer types.
  79987. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79988. r /= 255;
  79989. g /= 255;
  79990. b /= 255;
  79991. }
  79992. // Handle Gamma space textures.
  79993. if (cubeInfo.gammaSpace) {
  79994. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79995. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79996. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79997. }
  79998. var color = new BABYLON.Color3(r, g, b);
  79999. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  80000. totalSolidAngle += deltaSolidAngle;
  80001. u += du;
  80002. }
  80003. v += dv;
  80004. }
  80005. }
  80006. // Solid angle for entire sphere is 4*pi
  80007. var sphereSolidAngle = 4.0 * Math.PI;
  80008. // Adjust the solid angle to allow for how many faces we processed.
  80009. var facesProcessed = 6.0;
  80010. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  80011. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  80012. // This is needed because the numerical integration over the cube uses a
  80013. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  80014. // and also to compensate for accumulative error due to float precision in the summation.
  80015. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  80016. sphericalHarmonics.scale(correctionFactor);
  80017. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  80018. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  80019. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  80020. };
  80021. CubeMapToSphericalPolynomialTools.FileFaces = [
  80022. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  80023. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80024. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80025. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80026. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80027. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80028. ];
  80029. return CubeMapToSphericalPolynomialTools;
  80030. }());
  80031. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80032. })(BABYLON || (BABYLON = {}));
  80033. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80034. var BABYLON;
  80035. (function (BABYLON) {
  80036. /**
  80037. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80038. */
  80039. var PanoramaToCubeMapTools = /** @class */ (function () {
  80040. function PanoramaToCubeMapTools() {
  80041. }
  80042. /**
  80043. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80044. *
  80045. * @param float32Array The source data.
  80046. * @param inputWidth The width of the input panorama.
  80047. * @param inputhHeight The height of the input panorama.
  80048. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80049. * @return The cubemap data
  80050. */
  80051. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80052. if (!float32Array) {
  80053. throw "ConvertPanoramaToCubemap: input cannot be null";
  80054. }
  80055. if (float32Array.length != inputWidth * inputHeight * 3) {
  80056. throw "ConvertPanoramaToCubemap: input size is wrong";
  80057. }
  80058. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80059. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80060. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80061. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80062. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80063. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80064. return {
  80065. front: textureFront,
  80066. back: textureBack,
  80067. left: textureLeft,
  80068. right: textureRight,
  80069. up: textureUp,
  80070. down: textureDown,
  80071. size: size,
  80072. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80073. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80074. gammaSpace: false,
  80075. };
  80076. };
  80077. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80078. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80079. var textureArray = new Float32Array(buffer);
  80080. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80081. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80082. var dy = 1 / texSize;
  80083. var fy = 0;
  80084. for (var y = 0; y < texSize; y++) {
  80085. var xv1 = faceData[0];
  80086. var xv2 = faceData[2];
  80087. for (var x = 0; x < texSize; x++) {
  80088. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80089. v.normalize();
  80090. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80091. // 3 channels per pixels
  80092. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80093. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80094. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80095. xv1 = xv1.add(rotDX1);
  80096. xv2 = xv2.add(rotDX2);
  80097. }
  80098. fy += dy;
  80099. }
  80100. return textureArray;
  80101. };
  80102. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80103. var theta = Math.atan2(vDir.z, vDir.x);
  80104. var phi = Math.acos(vDir.y);
  80105. while (theta < -Math.PI)
  80106. theta += 2 * Math.PI;
  80107. while (theta > Math.PI)
  80108. theta -= 2 * Math.PI;
  80109. var dx = theta / Math.PI;
  80110. var dy = phi / Math.PI;
  80111. // recenter.
  80112. dx = dx * 0.5 + 0.5;
  80113. var px = Math.round(dx * inputWidth);
  80114. if (px < 0)
  80115. px = 0;
  80116. else if (px >= inputWidth)
  80117. px = inputWidth - 1;
  80118. var py = Math.round(dy * inputHeight);
  80119. if (py < 0)
  80120. py = 0;
  80121. else if (py >= inputHeight)
  80122. py = inputHeight - 1;
  80123. var inputY = (inputHeight - py - 1);
  80124. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80125. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80126. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80127. return {
  80128. r: r,
  80129. g: g,
  80130. b: b
  80131. };
  80132. };
  80133. PanoramaToCubeMapTools.FACE_FRONT = [
  80134. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80135. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80136. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80137. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80138. ];
  80139. PanoramaToCubeMapTools.FACE_BACK = [
  80140. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80141. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80142. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80143. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80144. ];
  80145. PanoramaToCubeMapTools.FACE_RIGHT = [
  80146. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80147. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80148. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80149. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80150. ];
  80151. PanoramaToCubeMapTools.FACE_LEFT = [
  80152. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80153. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80154. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80155. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80156. ];
  80157. PanoramaToCubeMapTools.FACE_DOWN = [
  80158. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80159. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80160. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80161. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80162. ];
  80163. PanoramaToCubeMapTools.FACE_UP = [
  80164. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80165. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80166. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80167. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80168. ];
  80169. return PanoramaToCubeMapTools;
  80170. }());
  80171. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80172. })(BABYLON || (BABYLON = {}));
  80173. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80174. var BABYLON;
  80175. (function (BABYLON) {
  80176. ;
  80177. /**
  80178. * This groups tools to convert HDR texture to native colors array.
  80179. */
  80180. var HDRTools = /** @class */ (function () {
  80181. function HDRTools() {
  80182. }
  80183. HDRTools.Ldexp = function (mantissa, exponent) {
  80184. if (exponent > 1023) {
  80185. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80186. }
  80187. if (exponent < -1074) {
  80188. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80189. }
  80190. return mantissa * Math.pow(2, exponent);
  80191. };
  80192. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80193. if (exponent > 0) { /*nonzero pixel*/
  80194. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80195. float32array[index + 0] = red * exponent;
  80196. float32array[index + 1] = green * exponent;
  80197. float32array[index + 2] = blue * exponent;
  80198. }
  80199. else {
  80200. float32array[index + 0] = 0;
  80201. float32array[index + 1] = 0;
  80202. float32array[index + 2] = 0;
  80203. }
  80204. };
  80205. HDRTools.readStringLine = function (uint8array, startIndex) {
  80206. var line = "";
  80207. var character = "";
  80208. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80209. character = String.fromCharCode(uint8array[i]);
  80210. if (character == "\n") {
  80211. break;
  80212. }
  80213. line += character;
  80214. }
  80215. return line;
  80216. };
  80217. /**
  80218. * Reads header information from an RGBE texture stored in a native array.
  80219. * More information on this format are available here:
  80220. * https://en.wikipedia.org/wiki/RGBE_image_format
  80221. *
  80222. * @param uint8array The binary file stored in native array.
  80223. * @return The header information.
  80224. */
  80225. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80226. var height = 0;
  80227. var width = 0;
  80228. var line = this.readStringLine(uint8array, 0);
  80229. if (line[0] != '#' || line[1] != '?') {
  80230. throw "Bad HDR Format.";
  80231. }
  80232. var endOfHeader = false;
  80233. var findFormat = false;
  80234. var lineIndex = 0;
  80235. do {
  80236. lineIndex += (line.length + 1);
  80237. line = this.readStringLine(uint8array, lineIndex);
  80238. if (line == "FORMAT=32-bit_rle_rgbe") {
  80239. findFormat = true;
  80240. }
  80241. else if (line.length == 0) {
  80242. endOfHeader = true;
  80243. }
  80244. } while (!endOfHeader);
  80245. if (!findFormat) {
  80246. throw "HDR Bad header format, unsupported FORMAT";
  80247. }
  80248. lineIndex += (line.length + 1);
  80249. line = this.readStringLine(uint8array, lineIndex);
  80250. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80251. var match = sizeRegexp.exec(line);
  80252. // TODO. Support +Y and -X if needed.
  80253. if (!match || match.length < 3) {
  80254. throw "HDR Bad header format, no size";
  80255. }
  80256. width = parseInt(match[2]);
  80257. height = parseInt(match[1]);
  80258. if (width < 8 || width > 0x7fff) {
  80259. throw "HDR Bad header format, unsupported size";
  80260. }
  80261. lineIndex += (line.length + 1);
  80262. return {
  80263. height: height,
  80264. width: width,
  80265. dataPosition: lineIndex
  80266. };
  80267. };
  80268. /**
  80269. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80270. * This RGBE texture needs to store the information as a panorama.
  80271. *
  80272. * More information on this format are available here:
  80273. * https://en.wikipedia.org/wiki/RGBE_image_format
  80274. *
  80275. * @param buffer The binary file stored in an array buffer.
  80276. * @param size The expected size of the extracted cubemap.
  80277. * @return The Cube Map information.
  80278. */
  80279. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80280. var uint8array = new Uint8Array(buffer);
  80281. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80282. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80283. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80284. return cubeMapData;
  80285. };
  80286. /**
  80287. * Returns the pixels data extracted from an RGBE texture.
  80288. * This pixels will be stored left to right up to down in the R G B order in one array.
  80289. *
  80290. * More information on this format are available here:
  80291. * https://en.wikipedia.org/wiki/RGBE_image_format
  80292. *
  80293. * @param uint8array The binary file stored in an array buffer.
  80294. * @param hdrInfo The header information of the file.
  80295. * @return The pixels data in RGB right to left up to down order.
  80296. */
  80297. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80298. // Keep for multi format supports.
  80299. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80300. };
  80301. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80302. var num_scanlines = hdrInfo.height;
  80303. var scanline_width = hdrInfo.width;
  80304. var a, b, c, d, count;
  80305. var dataIndex = hdrInfo.dataPosition;
  80306. var index = 0, endIndex = 0, i = 0;
  80307. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80308. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80309. // 3 channels of 4 bytes per pixel in float.
  80310. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80311. var resultArray = new Float32Array(resultBuffer);
  80312. // read in each successive scanline
  80313. while (num_scanlines > 0) {
  80314. a = uint8array[dataIndex++];
  80315. b = uint8array[dataIndex++];
  80316. c = uint8array[dataIndex++];
  80317. d = uint8array[dataIndex++];
  80318. if (a != 2 || b != 2 || (c & 0x80)) {
  80319. // this file is not run length encoded
  80320. throw "HDR Bad header format, not RLE";
  80321. }
  80322. if (((c << 8) | d) != scanline_width) {
  80323. throw "HDR Bad header format, wrong scan line width";
  80324. }
  80325. index = 0;
  80326. // read each of the four channels for the scanline into the buffer
  80327. for (i = 0; i < 4; i++) {
  80328. endIndex = (i + 1) * scanline_width;
  80329. while (index < endIndex) {
  80330. a = uint8array[dataIndex++];
  80331. b = uint8array[dataIndex++];
  80332. if (a > 128) {
  80333. // a run of the same value
  80334. count = a - 128;
  80335. if ((count == 0) || (count > endIndex - index)) {
  80336. throw "HDR Bad Format, bad scanline data (run)";
  80337. }
  80338. while (count-- > 0) {
  80339. scanLineArray[index++] = b;
  80340. }
  80341. }
  80342. else {
  80343. // a non-run
  80344. count = a;
  80345. if ((count == 0) || (count > endIndex - index)) {
  80346. throw "HDR Bad Format, bad scanline data (non-run)";
  80347. }
  80348. scanLineArray[index++] = b;
  80349. if (--count > 0) {
  80350. for (var j = 0; j < count; j++) {
  80351. scanLineArray[index++] = uint8array[dataIndex++];
  80352. }
  80353. }
  80354. }
  80355. }
  80356. }
  80357. // now convert data from buffer into floats
  80358. for (i = 0; i < scanline_width; i++) {
  80359. a = scanLineArray[i];
  80360. b = scanLineArray[i + scanline_width];
  80361. c = scanLineArray[i + 2 * scanline_width];
  80362. d = scanLineArray[i + 3 * scanline_width];
  80363. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80364. }
  80365. num_scanlines--;
  80366. }
  80367. return resultArray;
  80368. };
  80369. return HDRTools;
  80370. }());
  80371. BABYLON.HDRTools = HDRTools;
  80372. })(BABYLON || (BABYLON = {}));
  80373. //# sourceMappingURL=babylon.hdr.js.map
  80374. var BABYLON;
  80375. (function (BABYLON) {
  80376. /**
  80377. * This represents a texture coming from an HDR input.
  80378. *
  80379. * The only supported format is currently panorama picture stored in RGBE format.
  80380. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80381. */
  80382. var HDRCubeTexture = /** @class */ (function (_super) {
  80383. __extends(HDRCubeTexture, _super);
  80384. /**
  80385. * Instantiates an HDRTexture from the following parameters.
  80386. *
  80387. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80388. * @param scene The scene the texture will be used in
  80389. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80390. * @param noMipmap Forces to not generate the mipmap if true
  80391. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80392. * @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)
  80393. * @param reserved Reserved flag for internal use.
  80394. */
  80395. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80396. if (noMipmap === void 0) { noMipmap = false; }
  80397. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80398. if (gammaSpace === void 0) { gammaSpace = false; }
  80399. if (reserved === void 0) { reserved = false; }
  80400. if (onLoad === void 0) { onLoad = null; }
  80401. if (onError === void 0) { onError = null; }
  80402. var _this = _super.call(this, scene) || this;
  80403. _this._generateHarmonics = true;
  80404. _this._onLoad = null;
  80405. _this._onError = null;
  80406. /**
  80407. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80408. */
  80409. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80410. _this._isBlocking = true;
  80411. _this._rotationY = 0;
  80412. /**
  80413. * Gets or sets the center of the bounding box associated with the cube texture
  80414. * It must define where the camera used to render the texture was set
  80415. */
  80416. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80417. if (!url) {
  80418. return _this;
  80419. }
  80420. _this.name = url;
  80421. _this.url = url;
  80422. _this.hasAlpha = false;
  80423. _this.isCube = true;
  80424. _this._textureMatrix = BABYLON.Matrix.Identity();
  80425. _this._onLoad = onLoad;
  80426. _this._onError = onError;
  80427. _this.gammaSpace = gammaSpace;
  80428. _this._noMipmap = noMipmap;
  80429. _this._size = size;
  80430. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80431. if (!_this._texture) {
  80432. if (!scene.useDelayedTextureLoading) {
  80433. _this.loadTexture();
  80434. }
  80435. else {
  80436. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80437. }
  80438. }
  80439. return _this;
  80440. }
  80441. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80442. /**
  80443. * Gets wether or not the texture is blocking during loading.
  80444. */
  80445. get: function () {
  80446. return this._isBlocking;
  80447. },
  80448. /**
  80449. * Sets wether or not the texture is blocking during loading.
  80450. */
  80451. set: function (value) {
  80452. this._isBlocking = value;
  80453. },
  80454. enumerable: true,
  80455. configurable: true
  80456. });
  80457. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80458. /**
  80459. * Gets texture matrix rotation angle around Y axis radians.
  80460. */
  80461. get: function () {
  80462. return this._rotationY;
  80463. },
  80464. /**
  80465. * Sets texture matrix rotation angle around Y axis in radians.
  80466. */
  80467. set: function (value) {
  80468. this._rotationY = value;
  80469. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80470. },
  80471. enumerable: true,
  80472. configurable: true
  80473. });
  80474. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80475. get: function () {
  80476. return this._boundingBoxSize;
  80477. },
  80478. /**
  80479. * Gets or sets the size of the bounding box associated with the cube texture
  80480. * When defined, the cubemap will switch to local mode
  80481. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80482. * @example https://www.babylonjs-playground.com/#RNASML
  80483. */
  80484. set: function (value) {
  80485. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80486. return;
  80487. }
  80488. this._boundingBoxSize = value;
  80489. var scene = this.getScene();
  80490. if (scene) {
  80491. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80492. }
  80493. },
  80494. enumerable: true,
  80495. configurable: true
  80496. });
  80497. /**
  80498. * Occurs when the file is raw .hdr file.
  80499. */
  80500. HDRCubeTexture.prototype.loadTexture = function () {
  80501. var _this = this;
  80502. var callback = function (buffer) {
  80503. var scene = _this.getScene();
  80504. if (!scene) {
  80505. return null;
  80506. }
  80507. // Extract the raw linear data.
  80508. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80509. // Generate harmonics if needed.
  80510. if (_this._generateHarmonics) {
  80511. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80512. _this.sphericalPolynomial = sphericalPolynomial;
  80513. }
  80514. var results = [];
  80515. var byteArray = null;
  80516. // Push each faces.
  80517. for (var j = 0; j < 6; j++) {
  80518. // Create uintarray fallback.
  80519. if (!scene.getEngine().getCaps().textureFloat) {
  80520. // 3 channels of 1 bytes per pixel in bytes.
  80521. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80522. byteArray = new Uint8Array(byteBuffer);
  80523. }
  80524. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80525. // If special cases.
  80526. if (_this.gammaSpace || byteArray) {
  80527. for (var i = 0; i < _this._size * _this._size; i++) {
  80528. // Put in gamma space if requested.
  80529. if (_this.gammaSpace) {
  80530. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80531. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80532. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80533. }
  80534. // Convert to int texture for fallback.
  80535. if (byteArray) {
  80536. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80537. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80538. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80539. // May use luminance instead if the result is not accurate.
  80540. var max = Math.max(Math.max(r, g), b);
  80541. if (max > 255) {
  80542. var scale = 255 / max;
  80543. r *= scale;
  80544. g *= scale;
  80545. b *= scale;
  80546. }
  80547. byteArray[(i * 3) + 0] = r;
  80548. byteArray[(i * 3) + 1] = g;
  80549. byteArray[(i * 3) + 2] = b;
  80550. }
  80551. }
  80552. }
  80553. if (byteArray) {
  80554. results.push(byteArray);
  80555. }
  80556. else {
  80557. results.push(dataFace);
  80558. }
  80559. }
  80560. return results;
  80561. };
  80562. var scene = this.getScene();
  80563. if (scene) {
  80564. 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);
  80565. }
  80566. };
  80567. HDRCubeTexture.prototype.clone = function () {
  80568. var scene = this.getScene();
  80569. if (!scene) {
  80570. return this;
  80571. }
  80572. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80573. // Base texture
  80574. newTexture.level = this.level;
  80575. newTexture.wrapU = this.wrapU;
  80576. newTexture.wrapV = this.wrapV;
  80577. newTexture.coordinatesIndex = this.coordinatesIndex;
  80578. newTexture.coordinatesMode = this.coordinatesMode;
  80579. return newTexture;
  80580. };
  80581. // Methods
  80582. HDRCubeTexture.prototype.delayLoad = function () {
  80583. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80584. return;
  80585. }
  80586. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80587. this._texture = this._getFromCache(this.url, this._noMipmap);
  80588. if (!this._texture) {
  80589. this.loadTexture();
  80590. }
  80591. };
  80592. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80593. return this._textureMatrix;
  80594. };
  80595. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80596. this._textureMatrix = value;
  80597. };
  80598. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80599. var texture = null;
  80600. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80601. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80602. texture.name = parsedTexture.name;
  80603. texture.hasAlpha = parsedTexture.hasAlpha;
  80604. texture.level = parsedTexture.level;
  80605. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80606. texture.isBlocking = parsedTexture.isBlocking;
  80607. }
  80608. if (texture) {
  80609. if (parsedTexture.boundingBoxPosition) {
  80610. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80611. }
  80612. if (parsedTexture.boundingBoxSize) {
  80613. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80614. }
  80615. if (parsedTexture.rotationY) {
  80616. texture.rotationY = parsedTexture.rotationY;
  80617. }
  80618. }
  80619. return texture;
  80620. };
  80621. HDRCubeTexture.prototype.serialize = function () {
  80622. if (!this.name) {
  80623. return null;
  80624. }
  80625. var serializationObject = {};
  80626. serializationObject.name = this.name;
  80627. serializationObject.hasAlpha = this.hasAlpha;
  80628. serializationObject.isCube = true;
  80629. serializationObject.level = this.level;
  80630. serializationObject.size = this._size;
  80631. serializationObject.coordinatesMode = this.coordinatesMode;
  80632. serializationObject.useInGammaSpace = this.gammaSpace;
  80633. serializationObject.generateHarmonics = this._generateHarmonics;
  80634. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80635. serializationObject.noMipmap = this._noMipmap;
  80636. serializationObject.isBlocking = this._isBlocking;
  80637. serializationObject.rotationY = this._rotationY;
  80638. return serializationObject;
  80639. };
  80640. HDRCubeTexture._facesMapping = [
  80641. "right",
  80642. "left",
  80643. "up",
  80644. "down",
  80645. "front",
  80646. "back"
  80647. ];
  80648. return HDRCubeTexture;
  80649. }(BABYLON.BaseTexture));
  80650. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80651. })(BABYLON || (BABYLON = {}));
  80652. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80653. var BABYLON;
  80654. (function (BABYLON) {
  80655. var IndexedVector2 = /** @class */ (function (_super) {
  80656. __extends(IndexedVector2, _super);
  80657. function IndexedVector2(original, index) {
  80658. var _this = _super.call(this, original.x, original.y) || this;
  80659. _this.index = index;
  80660. return _this;
  80661. }
  80662. return IndexedVector2;
  80663. }(BABYLON.Vector2));
  80664. var PolygonPoints = /** @class */ (function () {
  80665. function PolygonPoints() {
  80666. this.elements = new Array();
  80667. }
  80668. PolygonPoints.prototype.add = function (originalPoints) {
  80669. var _this = this;
  80670. var result = new Array();
  80671. originalPoints.forEach(function (point) {
  80672. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80673. var newPoint = new IndexedVector2(point, _this.elements.length);
  80674. result.push(newPoint);
  80675. _this.elements.push(newPoint);
  80676. }
  80677. });
  80678. return result;
  80679. };
  80680. PolygonPoints.prototype.computeBounds = function () {
  80681. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80682. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80683. this.elements.forEach(function (point) {
  80684. // x
  80685. if (point.x < lmin.x) {
  80686. lmin.x = point.x;
  80687. }
  80688. else if (point.x > lmax.x) {
  80689. lmax.x = point.x;
  80690. }
  80691. // y
  80692. if (point.y < lmin.y) {
  80693. lmin.y = point.y;
  80694. }
  80695. else if (point.y > lmax.y) {
  80696. lmax.y = point.y;
  80697. }
  80698. });
  80699. return {
  80700. min: lmin,
  80701. max: lmax,
  80702. width: lmax.x - lmin.x,
  80703. height: lmax.y - lmin.y
  80704. };
  80705. };
  80706. return PolygonPoints;
  80707. }());
  80708. var Polygon = /** @class */ (function () {
  80709. function Polygon() {
  80710. }
  80711. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80712. return [
  80713. new BABYLON.Vector2(xmin, ymin),
  80714. new BABYLON.Vector2(xmax, ymin),
  80715. new BABYLON.Vector2(xmax, ymax),
  80716. new BABYLON.Vector2(xmin, ymax)
  80717. ];
  80718. };
  80719. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80720. if (cx === void 0) { cx = 0; }
  80721. if (cy === void 0) { cy = 0; }
  80722. if (numberOfSides === void 0) { numberOfSides = 32; }
  80723. var result = new Array();
  80724. var angle = 0;
  80725. var increment = (Math.PI * 2) / numberOfSides;
  80726. for (var i = 0; i < numberOfSides; i++) {
  80727. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80728. angle -= increment;
  80729. }
  80730. return result;
  80731. };
  80732. Polygon.Parse = function (input) {
  80733. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80734. var i, result = [];
  80735. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80736. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80737. }
  80738. return result;
  80739. };
  80740. Polygon.StartingAt = function (x, y) {
  80741. return BABYLON.Path2.StartingAt(x, y);
  80742. };
  80743. return Polygon;
  80744. }());
  80745. BABYLON.Polygon = Polygon;
  80746. var PolygonMeshBuilder = /** @class */ (function () {
  80747. function PolygonMeshBuilder(name, contours, scene) {
  80748. this._points = new PolygonPoints();
  80749. this._outlinepoints = new PolygonPoints();
  80750. this._holes = new Array();
  80751. this._epoints = new Array();
  80752. this._eholes = new Array();
  80753. this._name = name;
  80754. this._scene = scene;
  80755. var points;
  80756. if (contours instanceof BABYLON.Path2) {
  80757. points = contours.getPoints();
  80758. }
  80759. else {
  80760. points = contours;
  80761. }
  80762. this._addToepoint(points);
  80763. this._points.add(points);
  80764. this._outlinepoints.add(points);
  80765. if (typeof earcut === 'undefined') {
  80766. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80767. }
  80768. }
  80769. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80770. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80771. var p = points_1[_i];
  80772. this._epoints.push(p.x, p.y);
  80773. }
  80774. };
  80775. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80776. this._points.add(hole);
  80777. var holepoints = new PolygonPoints();
  80778. holepoints.add(hole);
  80779. this._holes.push(holepoints);
  80780. this._eholes.push(this._epoints.length / 2);
  80781. this._addToepoint(hole);
  80782. return this;
  80783. };
  80784. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80785. var _this = this;
  80786. if (updatable === void 0) { updatable = false; }
  80787. if (depth === void 0) { depth = 0; }
  80788. var result = new BABYLON.Mesh(this._name, this._scene);
  80789. var normals = new Array();
  80790. var positions = new Array();
  80791. var uvs = new Array();
  80792. var bounds = this._points.computeBounds();
  80793. this._points.elements.forEach(function (p) {
  80794. normals.push(0, 1.0, 0);
  80795. positions.push(p.x, 0, p.y);
  80796. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80797. });
  80798. var indices = new Array();
  80799. var res = earcut(this._epoints, this._eholes, 2);
  80800. for (var i = 0; i < res.length; i++) {
  80801. indices.push(res[i]);
  80802. }
  80803. if (depth > 0) {
  80804. var positionscount = (positions.length / 3); //get the current pointcount
  80805. this._points.elements.forEach(function (p) {
  80806. normals.push(0, -1.0, 0);
  80807. positions.push(p.x, -depth, p.y);
  80808. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80809. });
  80810. var totalCount = indices.length;
  80811. for (var i = 0; i < totalCount; i += 3) {
  80812. var i0 = indices[i + 0];
  80813. var i1 = indices[i + 1];
  80814. var i2 = indices[i + 2];
  80815. indices.push(i2 + positionscount);
  80816. indices.push(i1 + positionscount);
  80817. indices.push(i0 + positionscount);
  80818. }
  80819. //Add the sides
  80820. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80821. this._holes.forEach(function (hole) {
  80822. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80823. });
  80824. }
  80825. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80826. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80827. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80828. result.setIndices(indices);
  80829. return result;
  80830. };
  80831. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80832. var StartIndex = positions.length / 3;
  80833. var ulength = 0;
  80834. for (var i = 0; i < points.elements.length; i++) {
  80835. var p = points.elements[i];
  80836. var p1;
  80837. if ((i + 1) > points.elements.length - 1) {
  80838. p1 = points.elements[0];
  80839. }
  80840. else {
  80841. p1 = points.elements[i + 1];
  80842. }
  80843. positions.push(p.x, 0, p.y);
  80844. positions.push(p.x, -depth, p.y);
  80845. positions.push(p1.x, 0, p1.y);
  80846. positions.push(p1.x, -depth, p1.y);
  80847. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80848. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80849. var v3 = v2.subtract(v1);
  80850. var v4 = new BABYLON.Vector3(0, 1, 0);
  80851. var vn = BABYLON.Vector3.Cross(v3, v4);
  80852. vn = vn.normalize();
  80853. uvs.push(ulength / bounds.width, 0);
  80854. uvs.push(ulength / bounds.width, 1);
  80855. ulength += v3.length();
  80856. uvs.push((ulength / bounds.width), 0);
  80857. uvs.push((ulength / bounds.width), 1);
  80858. if (!flip) {
  80859. normals.push(-vn.x, -vn.y, -vn.z);
  80860. normals.push(-vn.x, -vn.y, -vn.z);
  80861. normals.push(-vn.x, -vn.y, -vn.z);
  80862. normals.push(-vn.x, -vn.y, -vn.z);
  80863. indices.push(StartIndex);
  80864. indices.push(StartIndex + 1);
  80865. indices.push(StartIndex + 2);
  80866. indices.push(StartIndex + 1);
  80867. indices.push(StartIndex + 3);
  80868. indices.push(StartIndex + 2);
  80869. }
  80870. else {
  80871. normals.push(vn.x, vn.y, vn.z);
  80872. normals.push(vn.x, vn.y, vn.z);
  80873. normals.push(vn.x, vn.y, vn.z);
  80874. normals.push(vn.x, vn.y, vn.z);
  80875. indices.push(StartIndex);
  80876. indices.push(StartIndex + 2);
  80877. indices.push(StartIndex + 1);
  80878. indices.push(StartIndex + 1);
  80879. indices.push(StartIndex + 2);
  80880. indices.push(StartIndex + 3);
  80881. }
  80882. StartIndex += 4;
  80883. }
  80884. ;
  80885. };
  80886. return PolygonMeshBuilder;
  80887. }());
  80888. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80889. })(BABYLON || (BABYLON = {}));
  80890. //# sourceMappingURL=babylon.polygonMesh.js.map
  80891. var BABYLON;
  80892. (function (BABYLON) {
  80893. // Unique ID when we import meshes from Babylon to CSG
  80894. var currentCSGMeshId = 0;
  80895. // # class Vertex
  80896. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80897. // one to provide additional features like texture coordinates and vertex
  80898. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80899. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80900. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80901. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80902. // is not used anywhere else.
  80903. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80904. var Vertex = /** @class */ (function () {
  80905. function Vertex(pos, normal, uv) {
  80906. this.pos = pos;
  80907. this.normal = normal;
  80908. this.uv = uv;
  80909. }
  80910. Vertex.prototype.clone = function () {
  80911. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80912. };
  80913. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80914. // orientation of a polygon is flipped.
  80915. Vertex.prototype.flip = function () {
  80916. this.normal = this.normal.scale(-1);
  80917. };
  80918. // Create a new vertex between this vertex and `other` by linearly
  80919. // interpolating all properties using a parameter of `t`. Subclasses should
  80920. // override this to interpolate additional properties.
  80921. Vertex.prototype.interpolate = function (other, t) {
  80922. 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));
  80923. };
  80924. return Vertex;
  80925. }());
  80926. // # class Plane
  80927. // Represents a plane in 3D space.
  80928. var Plane = /** @class */ (function () {
  80929. function Plane(normal, w) {
  80930. this.normal = normal;
  80931. this.w = w;
  80932. }
  80933. Plane.FromPoints = function (a, b, c) {
  80934. var v0 = c.subtract(a);
  80935. var v1 = b.subtract(a);
  80936. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80937. return null;
  80938. }
  80939. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80940. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80941. };
  80942. Plane.prototype.clone = function () {
  80943. return new Plane(this.normal.clone(), this.w);
  80944. };
  80945. Plane.prototype.flip = function () {
  80946. this.normal.scaleInPlace(-1);
  80947. this.w = -this.w;
  80948. };
  80949. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80950. // fragments in the appropriate lists. Coplanar polygons go into either
  80951. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80952. // respect to this plane. Polygons in front or in back of this plane go into
  80953. // either `front` or `back`.
  80954. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80955. var COPLANAR = 0;
  80956. var FRONT = 1;
  80957. var BACK = 2;
  80958. var SPANNING = 3;
  80959. // Classify each point as well as the entire polygon into one of the above
  80960. // four classes.
  80961. var polygonType = 0;
  80962. var types = [];
  80963. var i;
  80964. var t;
  80965. for (i = 0; i < polygon.vertices.length; i++) {
  80966. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80967. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80968. polygonType |= type;
  80969. types.push(type);
  80970. }
  80971. // Put the polygon in the correct list, splitting it when necessary.
  80972. switch (polygonType) {
  80973. case COPLANAR:
  80974. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80975. break;
  80976. case FRONT:
  80977. front.push(polygon);
  80978. break;
  80979. case BACK:
  80980. back.push(polygon);
  80981. break;
  80982. case SPANNING:
  80983. var f = [], b = [];
  80984. for (i = 0; i < polygon.vertices.length; i++) {
  80985. var j = (i + 1) % polygon.vertices.length;
  80986. var ti = types[i], tj = types[j];
  80987. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80988. if (ti !== BACK)
  80989. f.push(vi);
  80990. if (ti !== FRONT)
  80991. b.push(ti !== BACK ? vi.clone() : vi);
  80992. if ((ti | tj) === SPANNING) {
  80993. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80994. var v = vi.interpolate(vj, t);
  80995. f.push(v);
  80996. b.push(v.clone());
  80997. }
  80998. }
  80999. var poly;
  81000. if (f.length >= 3) {
  81001. poly = new Polygon(f, polygon.shared);
  81002. if (poly.plane)
  81003. front.push(poly);
  81004. }
  81005. if (b.length >= 3) {
  81006. poly = new Polygon(b, polygon.shared);
  81007. if (poly.plane)
  81008. back.push(poly);
  81009. }
  81010. break;
  81011. }
  81012. };
  81013. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  81014. // point is on the plane.
  81015. Plane.EPSILON = 1e-5;
  81016. return Plane;
  81017. }());
  81018. // # class Polygon
  81019. // Represents a convex polygon. The vertices used to initialize a polygon must
  81020. // be coplanar and form a convex loop.
  81021. //
  81022. // Each convex polygon has a `shared` property, which is shared between all
  81023. // polygons that are clones of each other or were split from the same polygon.
  81024. // This can be used to define per-polygon properties (such as surface color).
  81025. var Polygon = /** @class */ (function () {
  81026. function Polygon(vertices, shared) {
  81027. this.vertices = vertices;
  81028. this.shared = shared;
  81029. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81030. }
  81031. Polygon.prototype.clone = function () {
  81032. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81033. return new Polygon(vertices, this.shared);
  81034. };
  81035. Polygon.prototype.flip = function () {
  81036. this.vertices.reverse().map(function (v) { v.flip(); });
  81037. this.plane.flip();
  81038. };
  81039. return Polygon;
  81040. }());
  81041. // # class Node
  81042. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81043. // by picking a polygon to split along. That polygon (and all other coplanar
  81044. // polygons) are added directly to that node and the other polygons are added to
  81045. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81046. // no distinction between internal and leaf nodes.
  81047. var Node = /** @class */ (function () {
  81048. function Node(polygons) {
  81049. this.plane = null;
  81050. this.front = null;
  81051. this.back = null;
  81052. this.polygons = new Array();
  81053. if (polygons) {
  81054. this.build(polygons);
  81055. }
  81056. }
  81057. Node.prototype.clone = function () {
  81058. var node = new Node();
  81059. node.plane = this.plane && this.plane.clone();
  81060. node.front = this.front && this.front.clone();
  81061. node.back = this.back && this.back.clone();
  81062. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81063. return node;
  81064. };
  81065. // Convert solid space to empty space and empty space to solid space.
  81066. Node.prototype.invert = function () {
  81067. for (var i = 0; i < this.polygons.length; i++) {
  81068. this.polygons[i].flip();
  81069. }
  81070. if (this.plane) {
  81071. this.plane.flip();
  81072. }
  81073. if (this.front) {
  81074. this.front.invert();
  81075. }
  81076. if (this.back) {
  81077. this.back.invert();
  81078. }
  81079. var temp = this.front;
  81080. this.front = this.back;
  81081. this.back = temp;
  81082. };
  81083. // Recursively remove all polygons in `polygons` that are inside this BSP
  81084. // tree.
  81085. Node.prototype.clipPolygons = function (polygons) {
  81086. if (!this.plane)
  81087. return polygons.slice();
  81088. var front = new Array(), back = new Array();
  81089. for (var i = 0; i < polygons.length; i++) {
  81090. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81091. }
  81092. if (this.front) {
  81093. front = this.front.clipPolygons(front);
  81094. }
  81095. if (this.back) {
  81096. back = this.back.clipPolygons(back);
  81097. }
  81098. else {
  81099. back = [];
  81100. }
  81101. return front.concat(back);
  81102. };
  81103. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81104. // `bsp`.
  81105. Node.prototype.clipTo = function (bsp) {
  81106. this.polygons = bsp.clipPolygons(this.polygons);
  81107. if (this.front)
  81108. this.front.clipTo(bsp);
  81109. if (this.back)
  81110. this.back.clipTo(bsp);
  81111. };
  81112. // Return a list of all polygons in this BSP tree.
  81113. Node.prototype.allPolygons = function () {
  81114. var polygons = this.polygons.slice();
  81115. if (this.front)
  81116. polygons = polygons.concat(this.front.allPolygons());
  81117. if (this.back)
  81118. polygons = polygons.concat(this.back.allPolygons());
  81119. return polygons;
  81120. };
  81121. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81122. // new polygons are filtered down to the bottom of the tree and become new
  81123. // nodes there. Each set of polygons is partitioned using the first polygon
  81124. // (no heuristic is used to pick a good split).
  81125. Node.prototype.build = function (polygons) {
  81126. if (!polygons.length)
  81127. return;
  81128. if (!this.plane)
  81129. this.plane = polygons[0].plane.clone();
  81130. var front = new Array(), back = new Array();
  81131. for (var i = 0; i < polygons.length; i++) {
  81132. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81133. }
  81134. if (front.length) {
  81135. if (!this.front)
  81136. this.front = new Node();
  81137. this.front.build(front);
  81138. }
  81139. if (back.length) {
  81140. if (!this.back)
  81141. this.back = new Node();
  81142. this.back.build(back);
  81143. }
  81144. };
  81145. return Node;
  81146. }());
  81147. var CSG = /** @class */ (function () {
  81148. function CSG() {
  81149. this.polygons = new Array();
  81150. }
  81151. // Convert BABYLON.Mesh to BABYLON.CSG
  81152. CSG.FromMesh = function (mesh) {
  81153. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81154. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81155. if (mesh instanceof BABYLON.Mesh) {
  81156. mesh.computeWorldMatrix(true);
  81157. matrix = mesh.getWorldMatrix();
  81158. meshPosition = mesh.position.clone();
  81159. meshRotation = mesh.rotation.clone();
  81160. if (mesh.rotationQuaternion) {
  81161. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81162. }
  81163. meshScaling = mesh.scaling.clone();
  81164. }
  81165. else {
  81166. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81167. }
  81168. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81169. var subMeshes = mesh.subMeshes;
  81170. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81171. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81172. vertices = [];
  81173. for (var j = 0; j < 3; j++) {
  81174. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81175. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81176. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81177. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81178. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81179. vertex = new Vertex(position, normal, uv);
  81180. vertices.push(vertex);
  81181. }
  81182. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81183. // To handle the case of degenerated triangle
  81184. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81185. if (polygon.plane)
  81186. polygons.push(polygon);
  81187. }
  81188. }
  81189. var csg = CSG.FromPolygons(polygons);
  81190. csg.matrix = matrix;
  81191. csg.position = meshPosition;
  81192. csg.rotation = meshRotation;
  81193. csg.scaling = meshScaling;
  81194. csg.rotationQuaternion = meshRotationQuaternion;
  81195. currentCSGMeshId++;
  81196. return csg;
  81197. };
  81198. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81199. CSG.FromPolygons = function (polygons) {
  81200. var csg = new CSG();
  81201. csg.polygons = polygons;
  81202. return csg;
  81203. };
  81204. CSG.prototype.clone = function () {
  81205. var csg = new CSG();
  81206. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81207. csg.copyTransformAttributes(this);
  81208. return csg;
  81209. };
  81210. CSG.prototype.union = function (csg) {
  81211. var a = new Node(this.clone().polygons);
  81212. var b = new Node(csg.clone().polygons);
  81213. a.clipTo(b);
  81214. b.clipTo(a);
  81215. b.invert();
  81216. b.clipTo(a);
  81217. b.invert();
  81218. a.build(b.allPolygons());
  81219. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81220. };
  81221. CSG.prototype.unionInPlace = function (csg) {
  81222. var a = new Node(this.polygons);
  81223. var b = new Node(csg.polygons);
  81224. a.clipTo(b);
  81225. b.clipTo(a);
  81226. b.invert();
  81227. b.clipTo(a);
  81228. b.invert();
  81229. a.build(b.allPolygons());
  81230. this.polygons = a.allPolygons();
  81231. };
  81232. CSG.prototype.subtract = function (csg) {
  81233. var a = new Node(this.clone().polygons);
  81234. var b = new Node(csg.clone().polygons);
  81235. a.invert();
  81236. a.clipTo(b);
  81237. b.clipTo(a);
  81238. b.invert();
  81239. b.clipTo(a);
  81240. b.invert();
  81241. a.build(b.allPolygons());
  81242. a.invert();
  81243. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81244. };
  81245. CSG.prototype.subtractInPlace = function (csg) {
  81246. var a = new Node(this.polygons);
  81247. var b = new Node(csg.polygons);
  81248. a.invert();
  81249. a.clipTo(b);
  81250. b.clipTo(a);
  81251. b.invert();
  81252. b.clipTo(a);
  81253. b.invert();
  81254. a.build(b.allPolygons());
  81255. a.invert();
  81256. this.polygons = a.allPolygons();
  81257. };
  81258. CSG.prototype.intersect = function (csg) {
  81259. var a = new Node(this.clone().polygons);
  81260. var b = new Node(csg.clone().polygons);
  81261. a.invert();
  81262. b.clipTo(a);
  81263. b.invert();
  81264. a.clipTo(b);
  81265. b.clipTo(a);
  81266. a.build(b.allPolygons());
  81267. a.invert();
  81268. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81269. };
  81270. CSG.prototype.intersectInPlace = function (csg) {
  81271. var a = new Node(this.polygons);
  81272. var b = new Node(csg.polygons);
  81273. a.invert();
  81274. b.clipTo(a);
  81275. b.invert();
  81276. a.clipTo(b);
  81277. b.clipTo(a);
  81278. a.build(b.allPolygons());
  81279. a.invert();
  81280. this.polygons = a.allPolygons();
  81281. };
  81282. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81283. // not modified.
  81284. CSG.prototype.inverse = function () {
  81285. var csg = this.clone();
  81286. csg.inverseInPlace();
  81287. return csg;
  81288. };
  81289. CSG.prototype.inverseInPlace = function () {
  81290. this.polygons.map(function (p) { p.flip(); });
  81291. };
  81292. // This is used to keep meshes transformations so they can be restored
  81293. // when we build back a Babylon Mesh
  81294. // NB : All CSG operations are performed in world coordinates
  81295. CSG.prototype.copyTransformAttributes = function (csg) {
  81296. this.matrix = csg.matrix;
  81297. this.position = csg.position;
  81298. this.rotation = csg.rotation;
  81299. this.scaling = csg.scaling;
  81300. this.rotationQuaternion = csg.rotationQuaternion;
  81301. return this;
  81302. };
  81303. // Build Raw mesh from CSG
  81304. // Coordinates here are in world space
  81305. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81306. var matrix = this.matrix.clone();
  81307. matrix.invert();
  81308. 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;
  81309. if (keepSubMeshes) {
  81310. // Sort Polygons, since subMeshes are indices range
  81311. polygons.sort(function (a, b) {
  81312. if (a.shared.meshId === b.shared.meshId) {
  81313. return a.shared.subMeshId - b.shared.subMeshId;
  81314. }
  81315. else {
  81316. return a.shared.meshId - b.shared.meshId;
  81317. }
  81318. });
  81319. }
  81320. for (var i = 0, il = polygons.length; i < il; i++) {
  81321. polygon = polygons[i];
  81322. // Building SubMeshes
  81323. if (!subMesh_dict[polygon.shared.meshId]) {
  81324. subMesh_dict[polygon.shared.meshId] = {};
  81325. }
  81326. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81327. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81328. indexStart: +Infinity,
  81329. indexEnd: -Infinity,
  81330. materialIndex: polygon.shared.materialIndex
  81331. };
  81332. }
  81333. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81334. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81335. polygonIndices[0] = 0;
  81336. polygonIndices[1] = j - 1;
  81337. polygonIndices[2] = j;
  81338. for (var k = 0; k < 3; k++) {
  81339. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81340. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81341. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81342. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81343. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81344. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81345. // Check if 2 points can be merged
  81346. if (!(typeof vertex_idx !== 'undefined' &&
  81347. normals[vertex_idx * 3] === localNormal.x &&
  81348. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81349. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81350. uvs[vertex_idx * 2] === uv.x &&
  81351. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81352. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81353. uvs.push(uv.x, uv.y);
  81354. normals.push(normal.x, normal.y, normal.z);
  81355. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81356. }
  81357. indices.push(vertex_idx);
  81358. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81359. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81360. currentIndex++;
  81361. }
  81362. }
  81363. }
  81364. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81365. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81366. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81367. mesh.setIndices(indices, null);
  81368. if (keepSubMeshes) {
  81369. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81370. var materialIndexOffset = 0, materialMaxIndex;
  81371. mesh.subMeshes = new Array();
  81372. for (var m in subMesh_dict) {
  81373. materialMaxIndex = -1;
  81374. for (var sm in subMesh_dict[m]) {
  81375. subMesh_obj = subMesh_dict[m][sm];
  81376. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81377. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81378. }
  81379. materialIndexOffset += ++materialMaxIndex;
  81380. }
  81381. }
  81382. return mesh;
  81383. };
  81384. // Build Mesh from CSG taking material and transforms into account
  81385. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81386. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81387. mesh.material = material;
  81388. mesh.position.copyFrom(this.position);
  81389. mesh.rotation.copyFrom(this.rotation);
  81390. if (this.rotationQuaternion) {
  81391. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81392. }
  81393. mesh.scaling.copyFrom(this.scaling);
  81394. mesh.computeWorldMatrix(true);
  81395. return mesh;
  81396. };
  81397. return CSG;
  81398. }());
  81399. BABYLON.CSG = CSG;
  81400. })(BABYLON || (BABYLON = {}));
  81401. //# sourceMappingURL=babylon.csg.js.map
  81402. var BABYLON;
  81403. (function (BABYLON) {
  81404. var LensFlare = /** @class */ (function () {
  81405. function LensFlare(size, position, color, imgUrl, system) {
  81406. this.size = size;
  81407. this.position = position;
  81408. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81409. this.color = color || new BABYLON.Color3(1, 1, 1);
  81410. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81411. this._system = system;
  81412. system.lensFlares.push(this);
  81413. }
  81414. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81415. return new LensFlare(size, position, color, imgUrl, system);
  81416. };
  81417. LensFlare.prototype.dispose = function () {
  81418. if (this.texture) {
  81419. this.texture.dispose();
  81420. }
  81421. // Remove from scene
  81422. var index = this._system.lensFlares.indexOf(this);
  81423. this._system.lensFlares.splice(index, 1);
  81424. };
  81425. ;
  81426. return LensFlare;
  81427. }());
  81428. BABYLON.LensFlare = LensFlare;
  81429. })(BABYLON || (BABYLON = {}));
  81430. //# sourceMappingURL=babylon.lensFlare.js.map
  81431. var BABYLON;
  81432. (function (BABYLON) {
  81433. var LensFlareSystem = /** @class */ (function () {
  81434. function LensFlareSystem(name, emitter, scene) {
  81435. this.name = name;
  81436. this.lensFlares = new Array();
  81437. this.borderLimit = 300;
  81438. this.viewportBorder = 0;
  81439. this.layerMask = 0x0FFFFFFF;
  81440. this._vertexBuffers = {};
  81441. this._isEnabled = true;
  81442. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81443. this._emitter = emitter;
  81444. this.id = name;
  81445. scene.lensFlareSystems.push(this);
  81446. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81447. var engine = scene.getEngine();
  81448. // VBO
  81449. var vertices = [];
  81450. vertices.push(1, 1);
  81451. vertices.push(-1, 1);
  81452. vertices.push(-1, -1);
  81453. vertices.push(1, -1);
  81454. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81455. // Indices
  81456. var indices = [];
  81457. indices.push(0);
  81458. indices.push(1);
  81459. indices.push(2);
  81460. indices.push(0);
  81461. indices.push(2);
  81462. indices.push(3);
  81463. this._indexBuffer = engine.createIndexBuffer(indices);
  81464. // Effects
  81465. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81466. }
  81467. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81468. get: function () {
  81469. return this._isEnabled;
  81470. },
  81471. set: function (value) {
  81472. this._isEnabled = value;
  81473. },
  81474. enumerable: true,
  81475. configurable: true
  81476. });
  81477. LensFlareSystem.prototype.getScene = function () {
  81478. return this._scene;
  81479. };
  81480. LensFlareSystem.prototype.getEmitter = function () {
  81481. return this._emitter;
  81482. };
  81483. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81484. this._emitter = newEmitter;
  81485. };
  81486. LensFlareSystem.prototype.getEmitterPosition = function () {
  81487. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81488. };
  81489. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81490. var position = this.getEmitterPosition();
  81491. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81492. this._positionX = position.x;
  81493. this._positionY = position.y;
  81494. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81495. if (this.viewportBorder > 0) {
  81496. globalViewport.x -= this.viewportBorder;
  81497. globalViewport.y -= this.viewportBorder;
  81498. globalViewport.width += this.viewportBorder * 2;
  81499. globalViewport.height += this.viewportBorder * 2;
  81500. position.x += this.viewportBorder;
  81501. position.y += this.viewportBorder;
  81502. this._positionX += this.viewportBorder;
  81503. this._positionY += this.viewportBorder;
  81504. }
  81505. if (position.z > 0) {
  81506. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81507. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81508. return true;
  81509. }
  81510. return true;
  81511. }
  81512. return false;
  81513. };
  81514. LensFlareSystem.prototype._isVisible = function () {
  81515. if (!this._isEnabled || !this._scene.activeCamera) {
  81516. return false;
  81517. }
  81518. var emitterPosition = this.getEmitterPosition();
  81519. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81520. var distance = direction.length();
  81521. direction.normalize();
  81522. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81523. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81524. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81525. };
  81526. LensFlareSystem.prototype.render = function () {
  81527. if (!this._effect.isReady() || !this._scene.activeCamera)
  81528. return false;
  81529. var engine = this._scene.getEngine();
  81530. var viewport = this._scene.activeCamera.viewport;
  81531. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81532. // Position
  81533. if (!this.computeEffectivePosition(globalViewport)) {
  81534. return false;
  81535. }
  81536. // Visibility
  81537. if (!this._isVisible()) {
  81538. return false;
  81539. }
  81540. // Intensity
  81541. var awayX;
  81542. var awayY;
  81543. if (this._positionX < this.borderLimit + globalViewport.x) {
  81544. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81545. }
  81546. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81547. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81548. }
  81549. else {
  81550. awayX = 0;
  81551. }
  81552. if (this._positionY < this.borderLimit + globalViewport.y) {
  81553. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81554. }
  81555. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81556. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81557. }
  81558. else {
  81559. awayY = 0;
  81560. }
  81561. var away = (awayX > awayY) ? awayX : awayY;
  81562. away -= this.viewportBorder;
  81563. if (away > this.borderLimit) {
  81564. away = this.borderLimit;
  81565. }
  81566. var intensity = 1.0 - (away / this.borderLimit);
  81567. if (intensity < 0) {
  81568. return false;
  81569. }
  81570. if (intensity > 1.0) {
  81571. intensity = 1.0;
  81572. }
  81573. if (this.viewportBorder > 0) {
  81574. globalViewport.x += this.viewportBorder;
  81575. globalViewport.y += this.viewportBorder;
  81576. globalViewport.width -= this.viewportBorder * 2;
  81577. globalViewport.height -= this.viewportBorder * 2;
  81578. this._positionX -= this.viewportBorder;
  81579. this._positionY -= this.viewportBorder;
  81580. }
  81581. // Position
  81582. var centerX = globalViewport.x + globalViewport.width / 2;
  81583. var centerY = globalViewport.y + globalViewport.height / 2;
  81584. var distX = centerX - this._positionX;
  81585. var distY = centerY - this._positionY;
  81586. // Effects
  81587. engine.enableEffect(this._effect);
  81588. engine.setState(false);
  81589. engine.setDepthBuffer(false);
  81590. // VBOs
  81591. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81592. // Flares
  81593. for (var index = 0; index < this.lensFlares.length; index++) {
  81594. var flare = this.lensFlares[index];
  81595. engine.setAlphaMode(flare.alphaMode);
  81596. var x = centerX - (distX * flare.position);
  81597. var y = centerY - (distY * flare.position);
  81598. var cw = flare.size;
  81599. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81600. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81601. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81602. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81603. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81604. // Texture
  81605. this._effect.setTexture("textureSampler", flare.texture);
  81606. // Color
  81607. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81608. // Draw order
  81609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81610. }
  81611. engine.setDepthBuffer(true);
  81612. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81613. return true;
  81614. };
  81615. LensFlareSystem.prototype.dispose = function () {
  81616. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81617. if (vertexBuffer) {
  81618. vertexBuffer.dispose();
  81619. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81620. }
  81621. if (this._indexBuffer) {
  81622. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81623. this._indexBuffer = null;
  81624. }
  81625. while (this.lensFlares.length) {
  81626. this.lensFlares[0].dispose();
  81627. }
  81628. // Remove from scene
  81629. var index = this._scene.lensFlareSystems.indexOf(this);
  81630. this._scene.lensFlareSystems.splice(index, 1);
  81631. };
  81632. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81633. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81634. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81635. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81636. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81637. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81638. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81639. var parsedFlare = parsedLensFlareSystem.flares[index];
  81640. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81641. }
  81642. return lensFlareSystem;
  81643. };
  81644. LensFlareSystem.prototype.serialize = function () {
  81645. var serializationObject = {};
  81646. serializationObject.id = this.id;
  81647. serializationObject.name = this.name;
  81648. serializationObject.emitterId = this.getEmitter().id;
  81649. serializationObject.borderLimit = this.borderLimit;
  81650. serializationObject.flares = [];
  81651. for (var index = 0; index < this.lensFlares.length; index++) {
  81652. var flare = this.lensFlares[index];
  81653. serializationObject.flares.push({
  81654. size: flare.size,
  81655. position: flare.position,
  81656. color: flare.color.asArray(),
  81657. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81658. });
  81659. }
  81660. return serializationObject;
  81661. };
  81662. return LensFlareSystem;
  81663. }());
  81664. BABYLON.LensFlareSystem = LensFlareSystem;
  81665. })(BABYLON || (BABYLON = {}));
  81666. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81667. var BABYLON;
  81668. (function (BABYLON) {
  81669. /**
  81670. * This is a holder class for the physics joint created by the physics plugin.
  81671. * It holds a set of functions to control the underlying joint.
  81672. */
  81673. var PhysicsJoint = /** @class */ (function () {
  81674. function PhysicsJoint(type, jointData) {
  81675. this.type = type;
  81676. this.jointData = jointData;
  81677. jointData.nativeParams = jointData.nativeParams || {};
  81678. }
  81679. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81680. get: function () {
  81681. return this._physicsJoint;
  81682. },
  81683. set: function (newJoint) {
  81684. if (this._physicsJoint) {
  81685. //remove from the wolrd
  81686. }
  81687. this._physicsJoint = newJoint;
  81688. },
  81689. enumerable: true,
  81690. configurable: true
  81691. });
  81692. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81693. set: function (physicsPlugin) {
  81694. this._physicsPlugin = physicsPlugin;
  81695. },
  81696. enumerable: true,
  81697. configurable: true
  81698. });
  81699. /**
  81700. * Execute a function that is physics-plugin specific.
  81701. * @param {Function} func the function that will be executed.
  81702. * It accepts two parameters: the physics world and the physics joint.
  81703. */
  81704. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81705. func(this._physicsPlugin.world, this._physicsJoint);
  81706. };
  81707. //TODO check if the native joints are the same
  81708. //Joint Types
  81709. PhysicsJoint.DistanceJoint = 0;
  81710. PhysicsJoint.HingeJoint = 1;
  81711. PhysicsJoint.BallAndSocketJoint = 2;
  81712. PhysicsJoint.WheelJoint = 3;
  81713. PhysicsJoint.SliderJoint = 4;
  81714. //OIMO
  81715. PhysicsJoint.PrismaticJoint = 5;
  81716. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81717. PhysicsJoint.UniversalJoint = 6;
  81718. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81719. //Cannon
  81720. //Similar to a Ball-Joint. Different in params
  81721. PhysicsJoint.PointToPointJoint = 8;
  81722. //Cannon only at the moment
  81723. PhysicsJoint.SpringJoint = 9;
  81724. PhysicsJoint.LockJoint = 10;
  81725. return PhysicsJoint;
  81726. }());
  81727. BABYLON.PhysicsJoint = PhysicsJoint;
  81728. /**
  81729. * A class representing a physics distance joint.
  81730. */
  81731. var DistanceJoint = /** @class */ (function (_super) {
  81732. __extends(DistanceJoint, _super);
  81733. function DistanceJoint(jointData) {
  81734. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81735. }
  81736. /**
  81737. * Update the predefined distance.
  81738. */
  81739. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81740. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81741. };
  81742. return DistanceJoint;
  81743. }(PhysicsJoint));
  81744. BABYLON.DistanceJoint = DistanceJoint;
  81745. var MotorEnabledJoint = /** @class */ (function (_super) {
  81746. __extends(MotorEnabledJoint, _super);
  81747. function MotorEnabledJoint(type, jointData) {
  81748. return _super.call(this, type, jointData) || this;
  81749. }
  81750. /**
  81751. * Set the motor values.
  81752. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81753. * @param {number} force the force to apply
  81754. * @param {number} maxForce max force for this motor.
  81755. */
  81756. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81757. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81758. };
  81759. /**
  81760. * Set the motor's limits.
  81761. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81762. */
  81763. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81764. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81765. };
  81766. return MotorEnabledJoint;
  81767. }(PhysicsJoint));
  81768. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81769. /**
  81770. * This class represents a single hinge physics joint
  81771. */
  81772. var HingeJoint = /** @class */ (function (_super) {
  81773. __extends(HingeJoint, _super);
  81774. function HingeJoint(jointData) {
  81775. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81776. }
  81777. /**
  81778. * Set the motor values.
  81779. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81780. * @param {number} force the force to apply
  81781. * @param {number} maxForce max force for this motor.
  81782. */
  81783. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81784. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81785. };
  81786. /**
  81787. * Set the motor's limits.
  81788. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81789. */
  81790. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81791. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81792. };
  81793. return HingeJoint;
  81794. }(MotorEnabledJoint));
  81795. BABYLON.HingeJoint = HingeJoint;
  81796. /**
  81797. * This class represents a dual hinge physics joint (same as wheel joint)
  81798. */
  81799. var Hinge2Joint = /** @class */ (function (_super) {
  81800. __extends(Hinge2Joint, _super);
  81801. function Hinge2Joint(jointData) {
  81802. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81803. }
  81804. /**
  81805. * Set the motor values.
  81806. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81807. * @param {number} force the force to apply
  81808. * @param {number} maxForce max force for this motor.
  81809. * @param {motorIndex} the motor's index, 0 or 1.
  81810. */
  81811. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81812. if (motorIndex === void 0) { motorIndex = 0; }
  81813. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81814. };
  81815. /**
  81816. * Set the motor limits.
  81817. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81818. * @param {number} upperLimit the upper limit
  81819. * @param {number} lowerLimit lower limit
  81820. * @param {motorIndex} the motor's index, 0 or 1.
  81821. */
  81822. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81823. if (motorIndex === void 0) { motorIndex = 0; }
  81824. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81825. };
  81826. return Hinge2Joint;
  81827. }(MotorEnabledJoint));
  81828. BABYLON.Hinge2Joint = Hinge2Joint;
  81829. })(BABYLON || (BABYLON = {}));
  81830. //# sourceMappingURL=babylon.physicsJoint.js.map
  81831. var BABYLON;
  81832. (function (BABYLON) {
  81833. var PhysicsImpostor = /** @class */ (function () {
  81834. function PhysicsImpostor(object, type, _options, _scene) {
  81835. if (_options === void 0) { _options = { mass: 0 }; }
  81836. var _this = this;
  81837. this.object = object;
  81838. this.type = type;
  81839. this._options = _options;
  81840. this._scene = _scene;
  81841. this._bodyUpdateRequired = false;
  81842. this._onBeforePhysicsStepCallbacks = new Array();
  81843. this._onAfterPhysicsStepCallbacks = new Array();
  81844. this._onPhysicsCollideCallbacks = [];
  81845. this._deltaPosition = BABYLON.Vector3.Zero();
  81846. this._isDisposed = false;
  81847. //temp variables for parent rotation calculations
  81848. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81849. this._tmpQuat = new BABYLON.Quaternion();
  81850. this._tmpQuat2 = new BABYLON.Quaternion();
  81851. /**
  81852. * this function is executed by the physics engine.
  81853. */
  81854. this.beforeStep = function () {
  81855. if (!_this._physicsEngine) {
  81856. return;
  81857. }
  81858. _this.object.translate(_this._deltaPosition, -1);
  81859. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81860. _this.object.computeWorldMatrix(false);
  81861. if (_this.object.parent && _this.object.rotationQuaternion) {
  81862. _this.getParentsRotation();
  81863. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81864. }
  81865. else {
  81866. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81867. }
  81868. if (!_this._options.disableBidirectionalTransformation) {
  81869. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81870. }
  81871. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81872. func(_this);
  81873. });
  81874. };
  81875. /**
  81876. * this function is executed by the physics engine.
  81877. */
  81878. this.afterStep = function () {
  81879. if (!_this._physicsEngine) {
  81880. return;
  81881. }
  81882. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81883. func(_this);
  81884. });
  81885. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81886. // object has now its world rotation. needs to be converted to local.
  81887. if (_this.object.parent && _this.object.rotationQuaternion) {
  81888. _this.getParentsRotation();
  81889. _this._tmpQuat.conjugateInPlace();
  81890. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81891. }
  81892. // take the position set and make it the absolute position of this object.
  81893. _this.object.setAbsolutePosition(_this.object.position);
  81894. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81895. _this.object.translate(_this._deltaPosition, 1);
  81896. };
  81897. /**
  81898. * Legacy collision detection event support
  81899. */
  81900. this.onCollideEvent = null;
  81901. //event and body object due to cannon's event-based architecture.
  81902. this.onCollide = function (e) {
  81903. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81904. return;
  81905. }
  81906. if (!_this._physicsEngine) {
  81907. return;
  81908. }
  81909. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81910. if (otherImpostor) {
  81911. // Legacy collision detection event support
  81912. if (_this.onCollideEvent) {
  81913. _this.onCollideEvent(_this, otherImpostor);
  81914. }
  81915. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81916. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81917. }).forEach(function (obj) {
  81918. obj.callback(_this, otherImpostor);
  81919. });
  81920. }
  81921. };
  81922. //sanity check!
  81923. if (!this.object) {
  81924. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81925. return;
  81926. }
  81927. //legacy support for old syntax.
  81928. if (!this._scene && object.getScene) {
  81929. this._scene = object.getScene();
  81930. }
  81931. if (!this._scene) {
  81932. return;
  81933. }
  81934. this._physicsEngine = this._scene.getPhysicsEngine();
  81935. if (!this._physicsEngine) {
  81936. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81937. }
  81938. else {
  81939. //set the object's quaternion, if not set
  81940. if (!this.object.rotationQuaternion) {
  81941. if (this.object.rotation) {
  81942. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81943. }
  81944. else {
  81945. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81946. }
  81947. }
  81948. //default options params
  81949. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81950. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81951. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81952. this._joints = [];
  81953. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81954. if (!this.object.parent || this._options.ignoreParent) {
  81955. this._init();
  81956. }
  81957. else if (this.object.parent.physicsImpostor) {
  81958. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81959. }
  81960. }
  81961. }
  81962. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81963. get: function () {
  81964. return this._isDisposed;
  81965. },
  81966. enumerable: true,
  81967. configurable: true
  81968. });
  81969. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81970. get: function () {
  81971. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81972. },
  81973. set: function (value) {
  81974. this.setMass(value);
  81975. },
  81976. enumerable: true,
  81977. configurable: true
  81978. });
  81979. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81980. get: function () {
  81981. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81982. },
  81983. set: function (value) {
  81984. if (!this._physicsEngine) {
  81985. return;
  81986. }
  81987. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81988. },
  81989. enumerable: true,
  81990. configurable: true
  81991. });
  81992. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81993. get: function () {
  81994. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81995. },
  81996. set: function (value) {
  81997. if (!this._physicsEngine) {
  81998. return;
  81999. }
  82000. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  82001. },
  82002. enumerable: true,
  82003. configurable: true
  82004. });
  82005. /**
  82006. * This function will completly initialize this impostor.
  82007. * It will create a new body - but only if this mesh has no parent.
  82008. * If it has, this impostor will not be used other than to define the impostor
  82009. * of the child mesh.
  82010. */
  82011. PhysicsImpostor.prototype._init = function () {
  82012. if (!this._physicsEngine) {
  82013. return;
  82014. }
  82015. this._physicsEngine.removeImpostor(this);
  82016. this.physicsBody = null;
  82017. this._parent = this._parent || this._getPhysicsParent();
  82018. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  82019. this._physicsEngine.addImpostor(this);
  82020. }
  82021. };
  82022. PhysicsImpostor.prototype._getPhysicsParent = function () {
  82023. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82024. var parentMesh = this.object.parent;
  82025. return parentMesh.physicsImpostor;
  82026. }
  82027. return null;
  82028. };
  82029. /**
  82030. * Should a new body be generated.
  82031. */
  82032. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82033. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82034. };
  82035. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82036. this.forceUpdate();
  82037. };
  82038. /**
  82039. * Force a regeneration of this or the parent's impostor's body.
  82040. * Use under cautious - This will remove all joints already implemented.
  82041. */
  82042. PhysicsImpostor.prototype.forceUpdate = function () {
  82043. this._init();
  82044. if (this.parent && !this._options.ignoreParent) {
  82045. this.parent.forceUpdate();
  82046. }
  82047. };
  82048. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82049. /*public get mesh(): AbstractMesh {
  82050. return this._mesh;
  82051. }*/
  82052. /**
  82053. * Gets the body that holds this impostor. Either its own, or its parent.
  82054. */
  82055. get: function () {
  82056. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82057. },
  82058. /**
  82059. * Set the physics body. Used mainly by the physics engine/plugin
  82060. */
  82061. set: function (physicsBody) {
  82062. if (this._physicsBody && this._physicsEngine) {
  82063. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82064. }
  82065. this._physicsBody = physicsBody;
  82066. this.resetUpdateFlags();
  82067. },
  82068. enumerable: true,
  82069. configurable: true
  82070. });
  82071. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82072. get: function () {
  82073. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82074. },
  82075. set: function (value) {
  82076. this._parent = value;
  82077. },
  82078. enumerable: true,
  82079. configurable: true
  82080. });
  82081. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82082. this._bodyUpdateRequired = false;
  82083. };
  82084. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82085. if (this.object.getBoundingInfo) {
  82086. var q = this.object.rotationQuaternion;
  82087. //reset rotation
  82088. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82089. //calculate the world matrix with no rotation
  82090. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82091. var boundingInfo = this.object.getBoundingInfo();
  82092. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82093. //bring back the rotation
  82094. this.object.rotationQuaternion = q;
  82095. //calculate the world matrix with the new rotation
  82096. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82097. return size;
  82098. }
  82099. else {
  82100. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82101. }
  82102. };
  82103. PhysicsImpostor.prototype.getObjectCenter = function () {
  82104. if (this.object.getBoundingInfo) {
  82105. var boundingInfo = this.object.getBoundingInfo();
  82106. return boundingInfo.boundingBox.centerWorld;
  82107. }
  82108. else {
  82109. return this.object.position;
  82110. }
  82111. };
  82112. /**
  82113. * Get a specific parametes from the options parameter.
  82114. */
  82115. PhysicsImpostor.prototype.getParam = function (paramName) {
  82116. return this._options[paramName];
  82117. };
  82118. /**
  82119. * Sets a specific parameter in the options given to the physics plugin
  82120. */
  82121. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82122. this._options[paramName] = value;
  82123. this._bodyUpdateRequired = true;
  82124. };
  82125. /**
  82126. * Specifically change the body's mass option. Won't recreate the physics body object
  82127. */
  82128. PhysicsImpostor.prototype.setMass = function (mass) {
  82129. if (this.getParam("mass") !== mass) {
  82130. this.setParam("mass", mass);
  82131. }
  82132. if (this._physicsEngine) {
  82133. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82134. }
  82135. };
  82136. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82137. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82138. };
  82139. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82140. if (this._physicsEngine) {
  82141. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82142. }
  82143. };
  82144. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82145. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82146. };
  82147. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82148. if (this._physicsEngine) {
  82149. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82150. }
  82151. };
  82152. /**
  82153. * Execute a function with the physics plugin native code.
  82154. * Provide a function the will have two variables - the world object and the physics body object.
  82155. */
  82156. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82157. if (this._physicsEngine) {
  82158. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82159. }
  82160. };
  82161. /**
  82162. * Register a function that will be executed before the physics world is stepping forward.
  82163. */
  82164. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82165. this._onBeforePhysicsStepCallbacks.push(func);
  82166. };
  82167. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82168. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82169. if (index > -1) {
  82170. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82171. }
  82172. else {
  82173. BABYLON.Tools.Warn("Function to remove was not found");
  82174. }
  82175. };
  82176. /**
  82177. * Register a function that will be executed after the physics step
  82178. */
  82179. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82180. this._onAfterPhysicsStepCallbacks.push(func);
  82181. };
  82182. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82183. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82184. if (index > -1) {
  82185. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82186. }
  82187. else {
  82188. BABYLON.Tools.Warn("Function to remove was not found");
  82189. }
  82190. };
  82191. /**
  82192. * register a function that will be executed when this impostor collides against a different body.
  82193. */
  82194. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82195. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82196. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82197. };
  82198. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82199. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82200. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82201. if (index > -1) {
  82202. this._onPhysicsCollideCallbacks.splice(index, 1);
  82203. }
  82204. else {
  82205. BABYLON.Tools.Warn("Function to remove was not found");
  82206. }
  82207. };
  82208. PhysicsImpostor.prototype.getParentsRotation = function () {
  82209. var parent = this.object.parent;
  82210. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82211. while (parent) {
  82212. if (parent.rotationQuaternion) {
  82213. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82214. }
  82215. else {
  82216. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82217. }
  82218. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82219. parent = parent.parent;
  82220. }
  82221. return this._tmpQuat;
  82222. };
  82223. /**
  82224. * Apply a force
  82225. */
  82226. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82227. if (this._physicsEngine) {
  82228. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82229. }
  82230. return this;
  82231. };
  82232. /**
  82233. * Apply an impulse
  82234. */
  82235. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82236. if (this._physicsEngine) {
  82237. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82238. }
  82239. return this;
  82240. };
  82241. /**
  82242. * A help function to create a joint.
  82243. */
  82244. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82245. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82246. this.addJoint(otherImpostor, joint);
  82247. return this;
  82248. };
  82249. /**
  82250. * Add a joint to this impostor with a different impostor.
  82251. */
  82252. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82253. this._joints.push({
  82254. otherImpostor: otherImpostor,
  82255. joint: joint
  82256. });
  82257. if (this._physicsEngine) {
  82258. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82259. }
  82260. return this;
  82261. };
  82262. /**
  82263. * Will keep this body still, in a sleep mode.
  82264. */
  82265. PhysicsImpostor.prototype.sleep = function () {
  82266. if (this._physicsEngine) {
  82267. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82268. }
  82269. return this;
  82270. };
  82271. /**
  82272. * Wake the body up.
  82273. */
  82274. PhysicsImpostor.prototype.wakeUp = function () {
  82275. if (this._physicsEngine) {
  82276. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82277. }
  82278. return this;
  82279. };
  82280. PhysicsImpostor.prototype.clone = function (newObject) {
  82281. if (!newObject)
  82282. return null;
  82283. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82284. };
  82285. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82286. var _this = this;
  82287. //no dispose if no physics engine is available.
  82288. if (!this._physicsEngine) {
  82289. return;
  82290. }
  82291. this._joints.forEach(function (j) {
  82292. if (_this._physicsEngine) {
  82293. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82294. }
  82295. });
  82296. //dispose the physics body
  82297. this._physicsEngine.removeImpostor(this);
  82298. if (this.parent) {
  82299. this.parent.forceUpdate();
  82300. }
  82301. else {
  82302. /*this._object.getChildMeshes().forEach(function(mesh) {
  82303. if (mesh.physicsImpostor) {
  82304. if (disposeChildren) {
  82305. mesh.physicsImpostor.dispose();
  82306. mesh.physicsImpostor = null;
  82307. }
  82308. }
  82309. })*/
  82310. }
  82311. this._isDisposed = true;
  82312. };
  82313. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82314. this._deltaPosition.copyFrom(position);
  82315. };
  82316. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82317. if (!this._deltaRotation) {
  82318. this._deltaRotation = new BABYLON.Quaternion();
  82319. }
  82320. this._deltaRotation.copyFrom(rotation);
  82321. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82322. };
  82323. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82324. if (this._physicsEngine) {
  82325. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82326. }
  82327. return this;
  82328. };
  82329. PhysicsImpostor.prototype.getRadius = function () {
  82330. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82331. };
  82332. /**
  82333. * Sync a bone with this impostor
  82334. * @param bone The bone to sync to the impostor.
  82335. * @param boneMesh The mesh that the bone is influencing.
  82336. * @param jointPivot The pivot of the joint / bone in local space.
  82337. * @param distToJoint Optional distance from the impostor to the joint.
  82338. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82339. */
  82340. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82341. var tempVec = PhysicsImpostor._tmpVecs[0];
  82342. var mesh = this.object;
  82343. if (mesh.rotationQuaternion) {
  82344. if (adjustRotation) {
  82345. var tempQuat = PhysicsImpostor._tmpQuat;
  82346. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82347. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82348. }
  82349. else {
  82350. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82351. }
  82352. }
  82353. tempVec.x = 0;
  82354. tempVec.y = 0;
  82355. tempVec.z = 0;
  82356. if (jointPivot) {
  82357. tempVec.x = jointPivot.x;
  82358. tempVec.y = jointPivot.y;
  82359. tempVec.z = jointPivot.z;
  82360. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82361. if (distToJoint === undefined || distToJoint === null) {
  82362. distToJoint = jointPivot.length();
  82363. }
  82364. tempVec.x *= distToJoint;
  82365. tempVec.y *= distToJoint;
  82366. tempVec.z *= distToJoint;
  82367. }
  82368. if (bone.getParent()) {
  82369. tempVec.addInPlace(mesh.getAbsolutePosition());
  82370. bone.setAbsolutePosition(tempVec, boneMesh);
  82371. }
  82372. else {
  82373. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82374. boneMesh.position.x -= tempVec.x;
  82375. boneMesh.position.y -= tempVec.y;
  82376. boneMesh.position.z -= tempVec.z;
  82377. }
  82378. };
  82379. /**
  82380. * Sync impostor to a bone
  82381. * @param bone The bone that the impostor will be synced to.
  82382. * @param boneMesh The mesh that the bone is influencing.
  82383. * @param jointPivot The pivot of the joint / bone in local space.
  82384. * @param distToJoint Optional distance from the impostor to the joint.
  82385. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82386. * @param boneAxis Optional vector3 axis the bone is aligned with
  82387. */
  82388. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82389. var mesh = this.object;
  82390. if (mesh.rotationQuaternion) {
  82391. if (adjustRotation) {
  82392. var tempQuat = PhysicsImpostor._tmpQuat;
  82393. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82394. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82395. }
  82396. else {
  82397. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82398. }
  82399. }
  82400. var pos = PhysicsImpostor._tmpVecs[0];
  82401. var boneDir = PhysicsImpostor._tmpVecs[1];
  82402. if (!boneAxis) {
  82403. boneAxis = PhysicsImpostor._tmpVecs[2];
  82404. boneAxis.x = 0;
  82405. boneAxis.y = 1;
  82406. boneAxis.z = 0;
  82407. }
  82408. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82409. bone.getAbsolutePositionToRef(boneMesh, pos);
  82410. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82411. distToJoint = jointPivot.length();
  82412. }
  82413. if (distToJoint !== undefined && distToJoint !== null) {
  82414. pos.x += boneDir.x * distToJoint;
  82415. pos.y += boneDir.y * distToJoint;
  82416. pos.z += boneDir.z * distToJoint;
  82417. }
  82418. mesh.setAbsolutePosition(pos);
  82419. };
  82420. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82421. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82422. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82423. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82424. //Impostor types
  82425. PhysicsImpostor.NoImpostor = 0;
  82426. PhysicsImpostor.SphereImpostor = 1;
  82427. PhysicsImpostor.BoxImpostor = 2;
  82428. PhysicsImpostor.PlaneImpostor = 3;
  82429. PhysicsImpostor.MeshImpostor = 4;
  82430. PhysicsImpostor.CylinderImpostor = 7;
  82431. PhysicsImpostor.ParticleImpostor = 8;
  82432. PhysicsImpostor.HeightmapImpostor = 9;
  82433. return PhysicsImpostor;
  82434. }());
  82435. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82436. })(BABYLON || (BABYLON = {}));
  82437. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82438. var BABYLON;
  82439. (function (BABYLON) {
  82440. var PhysicsEngine = /** @class */ (function () {
  82441. function PhysicsEngine(gravity, _physicsPlugin) {
  82442. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82443. this._physicsPlugin = _physicsPlugin;
  82444. //new methods and parameters
  82445. this._impostors = [];
  82446. this._joints = [];
  82447. if (!this._physicsPlugin.isSupported()) {
  82448. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82449. + "Please make sure it is included.");
  82450. }
  82451. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82452. this.setGravity(gravity);
  82453. this.setTimeStep();
  82454. }
  82455. PhysicsEngine.prototype.setGravity = function (gravity) {
  82456. this.gravity = gravity;
  82457. this._physicsPlugin.setGravity(this.gravity);
  82458. };
  82459. /**
  82460. * Set the time step of the physics engine.
  82461. * default is 1/60.
  82462. * To slow it down, enter 1/600 for example.
  82463. * To speed it up, 1/30
  82464. * @param {number} newTimeStep the new timestep to apply to this world.
  82465. */
  82466. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82467. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82468. this._physicsPlugin.setTimeStep(newTimeStep);
  82469. };
  82470. /**
  82471. * Get the time step of the physics engine.
  82472. */
  82473. PhysicsEngine.prototype.getTimeStep = function () {
  82474. return this._physicsPlugin.getTimeStep();
  82475. };
  82476. PhysicsEngine.prototype.dispose = function () {
  82477. this._impostors.forEach(function (impostor) {
  82478. impostor.dispose();
  82479. });
  82480. this._physicsPlugin.dispose();
  82481. };
  82482. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82483. return this._physicsPlugin.name;
  82484. };
  82485. /**
  82486. * Adding a new impostor for the impostor tracking.
  82487. * This will be done by the impostor itself.
  82488. * @param {PhysicsImpostor} impostor the impostor to add
  82489. */
  82490. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82491. impostor.uniqueId = this._impostors.push(impostor);
  82492. //if no parent, generate the body
  82493. if (!impostor.parent) {
  82494. this._physicsPlugin.generatePhysicsBody(impostor);
  82495. }
  82496. };
  82497. /**
  82498. * Remove an impostor from the engine.
  82499. * This impostor and its mesh will not longer be updated by the physics engine.
  82500. * @param {PhysicsImpostor} impostor the impostor to remove
  82501. */
  82502. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82503. var index = this._impostors.indexOf(impostor);
  82504. if (index > -1) {
  82505. var removed = this._impostors.splice(index, 1);
  82506. //Is it needed?
  82507. if (removed.length) {
  82508. //this will also remove it from the world.
  82509. removed[0].physicsBody = null;
  82510. }
  82511. }
  82512. };
  82513. /**
  82514. * Add a joint to the physics engine
  82515. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82516. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82517. * @param {PhysicsJoint} the joint that will connect both impostors.
  82518. */
  82519. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82520. var impostorJoint = {
  82521. mainImpostor: mainImpostor,
  82522. connectedImpostor: connectedImpostor,
  82523. joint: joint
  82524. };
  82525. joint.physicsPlugin = this._physicsPlugin;
  82526. this._joints.push(impostorJoint);
  82527. this._physicsPlugin.generateJoint(impostorJoint);
  82528. };
  82529. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82530. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82531. return (impostorJoint.connectedImpostor === connectedImpostor
  82532. && impostorJoint.joint === joint
  82533. && impostorJoint.mainImpostor === mainImpostor);
  82534. });
  82535. if (matchingJoints.length) {
  82536. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82537. //TODO remove it from the list as well
  82538. }
  82539. };
  82540. /**
  82541. * Called by the scene. no need to call it.
  82542. */
  82543. PhysicsEngine.prototype._step = function (delta) {
  82544. var _this = this;
  82545. //check if any mesh has no body / requires an update
  82546. this._impostors.forEach(function (impostor) {
  82547. if (impostor.isBodyInitRequired()) {
  82548. _this._physicsPlugin.generatePhysicsBody(impostor);
  82549. }
  82550. });
  82551. if (delta > 0.1) {
  82552. delta = 0.1;
  82553. }
  82554. else if (delta <= 0) {
  82555. delta = 1.0 / 60.0;
  82556. }
  82557. this._physicsPlugin.executeStep(delta, this._impostors);
  82558. };
  82559. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82560. return this._physicsPlugin;
  82561. };
  82562. PhysicsEngine.prototype.getImpostors = function () {
  82563. return this._impostors;
  82564. };
  82565. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82566. for (var i = 0; i < this._impostors.length; ++i) {
  82567. if (this._impostors[i].object === object) {
  82568. return this._impostors[i];
  82569. }
  82570. }
  82571. return null;
  82572. };
  82573. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82574. for (var i = 0; i < this._impostors.length; ++i) {
  82575. if (this._impostors[i].physicsBody === body) {
  82576. return this._impostors[i];
  82577. }
  82578. }
  82579. return null;
  82580. };
  82581. // Statics
  82582. PhysicsEngine.Epsilon = 0.001;
  82583. return PhysicsEngine;
  82584. }());
  82585. BABYLON.PhysicsEngine = PhysicsEngine;
  82586. })(BABYLON || (BABYLON = {}));
  82587. //# sourceMappingURL=babylon.physicsEngine.js.map
  82588. var BABYLON;
  82589. (function (BABYLON) {
  82590. var PhysicsHelper = /** @class */ (function () {
  82591. function PhysicsHelper(scene) {
  82592. this._scene = scene;
  82593. this._physicsEngine = this._scene.getPhysicsEngine();
  82594. if (!this._physicsEngine) {
  82595. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82596. }
  82597. }
  82598. /**
  82599. * @param {Vector3} origin the origin of the explosion
  82600. * @param {number} radius the explosion radius
  82601. * @param {number} strength the explosion strength
  82602. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82603. */
  82604. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82605. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82606. if (!this._physicsEngine) {
  82607. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82608. return null;
  82609. }
  82610. var impostors = this._physicsEngine.getImpostors();
  82611. if (impostors.length === 0) {
  82612. return null;
  82613. }
  82614. var event = new PhysicsRadialExplosionEvent(this._scene);
  82615. impostors.forEach(function (impostor) {
  82616. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82617. if (!impostorForceAndContactPoint) {
  82618. return;
  82619. }
  82620. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82621. });
  82622. event.dispose(false);
  82623. return event;
  82624. };
  82625. /**
  82626. * @param {Vector3} origin the origin of the explosion
  82627. * @param {number} radius the explosion radius
  82628. * @param {number} strength the explosion strength
  82629. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82630. */
  82631. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82632. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82633. if (!this._physicsEngine) {
  82634. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82635. return null;
  82636. }
  82637. var impostors = this._physicsEngine.getImpostors();
  82638. if (impostors.length === 0) {
  82639. return null;
  82640. }
  82641. var event = new PhysicsRadialExplosionEvent(this._scene);
  82642. impostors.forEach(function (impostor) {
  82643. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82644. if (!impostorForceAndContactPoint) {
  82645. return;
  82646. }
  82647. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82648. });
  82649. event.dispose(false);
  82650. return event;
  82651. };
  82652. /**
  82653. * @param {Vector3} origin the origin of the explosion
  82654. * @param {number} radius the explosion radius
  82655. * @param {number} strength the explosion strength
  82656. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82657. */
  82658. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82659. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82660. if (!this._physicsEngine) {
  82661. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82662. return null;
  82663. }
  82664. var impostors = this._physicsEngine.getImpostors();
  82665. if (impostors.length === 0) {
  82666. return null;
  82667. }
  82668. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82669. event.dispose(false);
  82670. return event;
  82671. };
  82672. /**
  82673. * @param {Vector3} origin the origin of the updraft
  82674. * @param {number} radius the radius of the updraft
  82675. * @param {number} strength the strength of the updraft
  82676. * @param {number} height the height of the updraft
  82677. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82678. */
  82679. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82680. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82681. if (!this._physicsEngine) {
  82682. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82683. return null;
  82684. }
  82685. if (this._physicsEngine.getImpostors().length === 0) {
  82686. return null;
  82687. }
  82688. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82689. event.dispose(false);
  82690. return event;
  82691. };
  82692. /**
  82693. * @param {Vector3} origin the of the vortex
  82694. * @param {number} radius the radius of the vortex
  82695. * @param {number} strength the strength of the vortex
  82696. * @param {number} height the height of the vortex
  82697. */
  82698. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82699. if (!this._physicsEngine) {
  82700. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82701. return null;
  82702. }
  82703. if (this._physicsEngine.getImpostors().length === 0) {
  82704. return null;
  82705. }
  82706. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82707. event.dispose(false);
  82708. return event;
  82709. };
  82710. return PhysicsHelper;
  82711. }());
  82712. BABYLON.PhysicsHelper = PhysicsHelper;
  82713. /***** Radial explosion *****/
  82714. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82715. function PhysicsRadialExplosionEvent(scene) {
  82716. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82717. this._rays = [];
  82718. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82719. this._scene = scene;
  82720. }
  82721. /**
  82722. * Returns the data related to the radial explosion event (sphere & rays).
  82723. * @returns {PhysicsRadialExplosionEventData}
  82724. */
  82725. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82726. this._dataFetched = true;
  82727. return {
  82728. sphere: this._sphere,
  82729. rays: this._rays,
  82730. };
  82731. };
  82732. /**
  82733. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82734. * @param impostor
  82735. * @param {Vector3} origin the origin of the explosion
  82736. * @param {number} radius the explosion radius
  82737. * @param {number} strength the explosion strength
  82738. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82739. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82740. */
  82741. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82742. if (impostor.mass === 0) {
  82743. return null;
  82744. }
  82745. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82746. return null;
  82747. }
  82748. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82749. return null;
  82750. }
  82751. var impostorObjectCenter = impostor.getObjectCenter();
  82752. var direction = impostorObjectCenter.subtract(origin);
  82753. var ray = new BABYLON.Ray(origin, direction, radius);
  82754. this._rays.push(ray);
  82755. var hit = ray.intersectsMesh(impostor.object);
  82756. var contactPoint = hit.pickedPoint;
  82757. if (!contactPoint) {
  82758. return null;
  82759. }
  82760. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82761. if (distanceFromOrigin > radius) {
  82762. return null;
  82763. }
  82764. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82765. ? strength
  82766. : strength * (1 - (distanceFromOrigin / radius));
  82767. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82768. return { force: force, contactPoint: contactPoint };
  82769. };
  82770. /**
  82771. * Disposes the sphere.
  82772. * @param {bolean} force
  82773. */
  82774. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82775. var _this = this;
  82776. if (force === void 0) { force = true; }
  82777. if (force) {
  82778. this._sphere.dispose();
  82779. }
  82780. else {
  82781. setTimeout(function () {
  82782. if (!_this._dataFetched) {
  82783. _this._sphere.dispose();
  82784. }
  82785. }, 0);
  82786. }
  82787. };
  82788. /*** Helpers ***/
  82789. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82790. if (!this._sphere) {
  82791. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82792. this._sphere.isVisible = false;
  82793. }
  82794. };
  82795. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82796. var impostorObject = impostor.object;
  82797. this._prepareSphere();
  82798. this._sphere.position = origin;
  82799. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82800. this._sphere._updateBoundingInfo();
  82801. this._sphere.computeWorldMatrix(true);
  82802. return this._sphere.intersectsMesh(impostorObject, true);
  82803. };
  82804. return PhysicsRadialExplosionEvent;
  82805. }());
  82806. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82807. /***** Gravitational Field *****/
  82808. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82809. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82810. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82811. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82812. this._physicsHelper = physicsHelper;
  82813. this._scene = scene;
  82814. this._origin = origin;
  82815. this._radius = radius;
  82816. this._strength = strength;
  82817. this._falloff = falloff;
  82818. this._tickCallback = this._tick.bind(this);
  82819. }
  82820. /**
  82821. * Returns the data related to the gravitational field event (sphere).
  82822. * @returns {PhysicsGravitationalFieldEventData}
  82823. */
  82824. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82825. this._dataFetched = true;
  82826. return {
  82827. sphere: this._sphere,
  82828. };
  82829. };
  82830. /**
  82831. * Enables the gravitational field.
  82832. */
  82833. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82834. this._tickCallback.call(this);
  82835. this._scene.registerBeforeRender(this._tickCallback);
  82836. };
  82837. /**
  82838. * Disables the gravitational field.
  82839. */
  82840. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82841. this._scene.unregisterBeforeRender(this._tickCallback);
  82842. };
  82843. /**
  82844. * Disposes the sphere.
  82845. * @param {bolean} force
  82846. */
  82847. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82848. var _this = this;
  82849. if (force === void 0) { force = true; }
  82850. if (force) {
  82851. this._sphere.dispose();
  82852. }
  82853. else {
  82854. setTimeout(function () {
  82855. if (!_this._dataFetched) {
  82856. _this._sphere.dispose();
  82857. }
  82858. }, 0);
  82859. }
  82860. };
  82861. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82862. // Since the params won't change, we fetch the event only once
  82863. if (this._sphere) {
  82864. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82865. }
  82866. else {
  82867. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82868. if (radialExplosionEvent) {
  82869. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82870. }
  82871. }
  82872. };
  82873. return PhysicsGravitationalFieldEvent;
  82874. }());
  82875. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82876. /***** Updraft *****/
  82877. var PhysicsUpdraftEvent = /** @class */ (function () {
  82878. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82879. this._scene = _scene;
  82880. this._origin = _origin;
  82881. this._radius = _radius;
  82882. this._strength = _strength;
  82883. this._height = _height;
  82884. this._updraftMode = _updraftMode;
  82885. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82886. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82887. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82888. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82889. this._physicsEngine = this._scene.getPhysicsEngine();
  82890. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82891. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82892. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82893. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82894. }
  82895. this._tickCallback = this._tick.bind(this);
  82896. }
  82897. /**
  82898. * Returns the data related to the updraft event (cylinder).
  82899. * @returns {PhysicsUpdraftEventData}
  82900. */
  82901. PhysicsUpdraftEvent.prototype.getData = function () {
  82902. this._dataFetched = true;
  82903. return {
  82904. cylinder: this._cylinder,
  82905. };
  82906. };
  82907. /**
  82908. * Enables the updraft.
  82909. */
  82910. PhysicsUpdraftEvent.prototype.enable = function () {
  82911. this._tickCallback.call(this);
  82912. this._scene.registerBeforeRender(this._tickCallback);
  82913. };
  82914. /**
  82915. * Disables the cortex.
  82916. */
  82917. PhysicsUpdraftEvent.prototype.disable = function () {
  82918. this._scene.unregisterBeforeRender(this._tickCallback);
  82919. };
  82920. /**
  82921. * Disposes the sphere.
  82922. * @param {bolean} force
  82923. */
  82924. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82925. var _this = this;
  82926. if (force === void 0) { force = true; }
  82927. if (force) {
  82928. this._cylinder.dispose();
  82929. }
  82930. else {
  82931. setTimeout(function () {
  82932. if (!_this._dataFetched) {
  82933. _this._cylinder.dispose();
  82934. }
  82935. }, 0);
  82936. }
  82937. };
  82938. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82939. if (impostor.mass === 0) {
  82940. return null;
  82941. }
  82942. if (!this._intersectsWithCylinder(impostor)) {
  82943. return null;
  82944. }
  82945. var impostorObjectCenter = impostor.getObjectCenter();
  82946. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82947. var direction = this._originDirection;
  82948. }
  82949. else {
  82950. var direction = impostorObjectCenter.subtract(this._originTop);
  82951. }
  82952. var multiplier = this._strength * -1;
  82953. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82954. return { force: force, contactPoint: impostorObjectCenter };
  82955. };
  82956. PhysicsUpdraftEvent.prototype._tick = function () {
  82957. var _this = this;
  82958. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82959. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82960. if (!impostorForceAndContactPoint) {
  82961. return;
  82962. }
  82963. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82964. });
  82965. };
  82966. /*** Helpers ***/
  82967. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82968. if (!this._cylinder) {
  82969. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82970. height: this._height,
  82971. diameter: this._radius * 2,
  82972. }, this._scene);
  82973. this._cylinder.isVisible = false;
  82974. }
  82975. };
  82976. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82977. var impostorObject = impostor.object;
  82978. this._prepareCylinder();
  82979. this._cylinder.position = this._cylinderPosition;
  82980. return this._cylinder.intersectsMesh(impostorObject, true);
  82981. };
  82982. return PhysicsUpdraftEvent;
  82983. }());
  82984. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82985. /***** Vortex *****/
  82986. var PhysicsVortexEvent = /** @class */ (function () {
  82987. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82988. this._scene = _scene;
  82989. this._origin = _origin;
  82990. this._radius = _radius;
  82991. this._strength = _strength;
  82992. this._height = _height;
  82993. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82994. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82995. this._updraftMultiplier = 0.02;
  82996. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82997. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82998. this._physicsEngine = this._scene.getPhysicsEngine();
  82999. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  83000. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  83001. this._tickCallback = this._tick.bind(this);
  83002. }
  83003. /**
  83004. * Returns the data related to the vortex event (cylinder).
  83005. * @returns {PhysicsVortexEventData}
  83006. */
  83007. PhysicsVortexEvent.prototype.getData = function () {
  83008. this._dataFetched = true;
  83009. return {
  83010. cylinder: this._cylinder,
  83011. };
  83012. };
  83013. /**
  83014. * Enables the vortex.
  83015. */
  83016. PhysicsVortexEvent.prototype.enable = function () {
  83017. this._tickCallback.call(this);
  83018. this._scene.registerBeforeRender(this._tickCallback);
  83019. };
  83020. /**
  83021. * Disables the cortex.
  83022. */
  83023. PhysicsVortexEvent.prototype.disable = function () {
  83024. this._scene.unregisterBeforeRender(this._tickCallback);
  83025. };
  83026. /**
  83027. * Disposes the sphere.
  83028. * @param {bolean} force
  83029. */
  83030. PhysicsVortexEvent.prototype.dispose = function (force) {
  83031. var _this = this;
  83032. if (force === void 0) { force = true; }
  83033. if (force) {
  83034. this._cylinder.dispose();
  83035. }
  83036. else {
  83037. setTimeout(function () {
  83038. if (!_this._dataFetched) {
  83039. _this._cylinder.dispose();
  83040. }
  83041. }, 0);
  83042. }
  83043. };
  83044. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83045. if (impostor.mass === 0) {
  83046. return null;
  83047. }
  83048. if (!this._intersectsWithCylinder(impostor)) {
  83049. return null;
  83050. }
  83051. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83052. return null;
  83053. }
  83054. var impostorObjectCenter = impostor.getObjectCenter();
  83055. 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)
  83056. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83057. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83058. var hit = ray.intersectsMesh(impostor.object);
  83059. var contactPoint = hit.pickedPoint;
  83060. if (!contactPoint) {
  83061. return null;
  83062. }
  83063. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83064. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83065. var directionToOrigin = contactPoint.normalize();
  83066. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83067. directionToOrigin = directionToOrigin.negate();
  83068. }
  83069. // TODO: find a more physically based solution
  83070. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83071. var forceX = directionToOrigin.x * this._strength / 8;
  83072. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83073. var forceZ = directionToOrigin.z * this._strength / 8;
  83074. }
  83075. else {
  83076. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83077. var forceY = this._originTop.y * this._updraftMultiplier;
  83078. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83079. }
  83080. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83081. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83082. return { force: force, contactPoint: impostorObjectCenter };
  83083. };
  83084. PhysicsVortexEvent.prototype._tick = function () {
  83085. var _this = this;
  83086. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83087. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83088. if (!impostorForceAndContactPoint) {
  83089. return;
  83090. }
  83091. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83092. });
  83093. };
  83094. /*** Helpers ***/
  83095. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83096. if (!this._cylinder) {
  83097. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83098. height: this._height,
  83099. diameter: this._radius * 2,
  83100. }, this._scene);
  83101. this._cylinder.isVisible = false;
  83102. }
  83103. };
  83104. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83105. var impostorObject = impostor.object;
  83106. this._prepareCylinder();
  83107. this._cylinder.position = this._cylinderPosition;
  83108. return this._cylinder.intersectsMesh(impostorObject, true);
  83109. };
  83110. return PhysicsVortexEvent;
  83111. }());
  83112. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83113. /***** Enums *****/
  83114. /**
  83115. * The strenght of the force in correspondence to the distance of the affected object
  83116. */
  83117. var PhysicsRadialImpulseFalloff;
  83118. (function (PhysicsRadialImpulseFalloff) {
  83119. /** Defines that impulse is constant in strength across it's whole radius */
  83120. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83121. /** DEfines that impulse gets weaker if it's further from the origin */
  83122. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83123. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83124. /**
  83125. * The strenght of the force in correspondence to the distance of the affected object
  83126. */
  83127. var PhysicsUpdraftMode;
  83128. (function (PhysicsUpdraftMode) {
  83129. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83130. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83131. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83132. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83133. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83134. })(BABYLON || (BABYLON = {}));
  83135. //# sourceMappingURL=babylon.physicsHelper.js.map
  83136. var BABYLON;
  83137. (function (BABYLON) {
  83138. var CannonJSPlugin = /** @class */ (function () {
  83139. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83140. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83141. if (iterations === void 0) { iterations = 10; }
  83142. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83143. this.name = "CannonJSPlugin";
  83144. this._physicsMaterials = new Array();
  83145. this._fixedTimeStep = 1 / 60;
  83146. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83147. this.BJSCANNON = CANNON;
  83148. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83149. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83150. this._tmpPosition = BABYLON.Vector3.Zero();
  83151. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83152. this._tmpUnityRotation = new BABYLON.Quaternion();
  83153. if (!this.isSupported()) {
  83154. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83155. return;
  83156. }
  83157. this._extendNamespace();
  83158. this.world = new this.BJSCANNON.World();
  83159. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83160. this.world.solver.iterations = iterations;
  83161. }
  83162. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83163. this.world.gravity.copy(gravity);
  83164. };
  83165. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83166. this._fixedTimeStep = timeStep;
  83167. };
  83168. CannonJSPlugin.prototype.getTimeStep = function () {
  83169. return this._fixedTimeStep;
  83170. };
  83171. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83172. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83173. };
  83174. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83175. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83176. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83177. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83178. };
  83179. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83180. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83181. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83182. impostor.physicsBody.applyForce(impulse, worldPoint);
  83183. };
  83184. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83185. //parent-child relationship. Does this impostor has a parent impostor?
  83186. if (impostor.parent) {
  83187. if (impostor.physicsBody) {
  83188. this.removePhysicsBody(impostor);
  83189. //TODO is that needed?
  83190. impostor.forceUpdate();
  83191. }
  83192. return;
  83193. }
  83194. //should a new body be created for this impostor?
  83195. if (impostor.isBodyInitRequired()) {
  83196. var shape = this._createShape(impostor);
  83197. //unregister events, if body is being changed
  83198. var oldBody = impostor.physicsBody;
  83199. if (oldBody) {
  83200. this.removePhysicsBody(impostor);
  83201. }
  83202. //create the body and material
  83203. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83204. var bodyCreationObject = {
  83205. mass: impostor.getParam("mass"),
  83206. material: material
  83207. };
  83208. // A simple extend, in case native options were used.
  83209. var nativeOptions = impostor.getParam("nativeOptions");
  83210. for (var key in nativeOptions) {
  83211. if (nativeOptions.hasOwnProperty(key)) {
  83212. bodyCreationObject[key] = nativeOptions[key];
  83213. }
  83214. }
  83215. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83216. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83217. this.world.addEventListener("preStep", impostor.beforeStep);
  83218. this.world.addEventListener("postStep", impostor.afterStep);
  83219. impostor.physicsBody.addShape(shape);
  83220. this.world.add(impostor.physicsBody);
  83221. //try to keep the body moving in the right direction by taking old properties.
  83222. //Should be tested!
  83223. if (oldBody) {
  83224. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83225. impostor.physicsBody[param].copy(oldBody[param]);
  83226. });
  83227. }
  83228. this._processChildMeshes(impostor);
  83229. }
  83230. //now update the body's transformation
  83231. this._updatePhysicsBodyTransformation(impostor);
  83232. };
  83233. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83234. var _this = this;
  83235. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83236. var currentRotation = mainImpostor.object.rotationQuaternion;
  83237. if (meshChildren.length) {
  83238. var processMesh = function (localPosition, mesh) {
  83239. if (!currentRotation || !mesh.rotationQuaternion) {
  83240. return;
  83241. }
  83242. var childImpostor = mesh.getPhysicsImpostor();
  83243. if (childImpostor) {
  83244. var parent = childImpostor.parent;
  83245. if (parent !== mainImpostor) {
  83246. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83247. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83248. if (childImpostor.physicsBody) {
  83249. _this.removePhysicsBody(childImpostor);
  83250. childImpostor.physicsBody = null;
  83251. }
  83252. childImpostor.parent = mainImpostor;
  83253. childImpostor.resetUpdateFlags();
  83254. 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));
  83255. //Add the mass of the children.
  83256. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83257. }
  83258. }
  83259. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83260. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83261. };
  83262. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83263. }
  83264. };
  83265. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83266. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83267. this.world.removeEventListener("preStep", impostor.beforeStep);
  83268. this.world.removeEventListener("postStep", impostor.afterStep);
  83269. this.world.remove(impostor.physicsBody);
  83270. };
  83271. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83272. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83273. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83274. if (!mainBody || !connectedBody) {
  83275. return;
  83276. }
  83277. var constraint;
  83278. var jointData = impostorJoint.joint.jointData;
  83279. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83280. var constraintData = {
  83281. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83282. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83283. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83284. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83285. maxForce: jointData.nativeParams.maxForce,
  83286. collideConnected: !!jointData.collision
  83287. };
  83288. switch (impostorJoint.joint.type) {
  83289. case BABYLON.PhysicsJoint.HingeJoint:
  83290. case BABYLON.PhysicsJoint.Hinge2Joint:
  83291. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83292. break;
  83293. case BABYLON.PhysicsJoint.DistanceJoint:
  83294. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83295. break;
  83296. case BABYLON.PhysicsJoint.SpringJoint:
  83297. var springData = jointData;
  83298. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83299. restLength: springData.length,
  83300. stiffness: springData.stiffness,
  83301. damping: springData.damping,
  83302. localAnchorA: constraintData.pivotA,
  83303. localAnchorB: constraintData.pivotB
  83304. });
  83305. break;
  83306. case BABYLON.PhysicsJoint.LockJoint:
  83307. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83308. break;
  83309. case BABYLON.PhysicsJoint.PointToPointJoint:
  83310. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83311. default:
  83312. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83313. break;
  83314. }
  83315. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83316. constraint.collideConnected = !!jointData.collision;
  83317. impostorJoint.joint.physicsJoint = constraint;
  83318. //don't add spring as constraint, as it is not one.
  83319. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83320. this.world.addConstraint(constraint);
  83321. }
  83322. else {
  83323. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83324. constraint.applyForce();
  83325. });
  83326. }
  83327. };
  83328. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83329. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83330. };
  83331. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83332. var index;
  83333. var mat;
  83334. for (index = 0; index < this._physicsMaterials.length; index++) {
  83335. mat = this._physicsMaterials[index];
  83336. if (mat.friction === friction && mat.restitution === restitution) {
  83337. return mat;
  83338. }
  83339. }
  83340. var currentMat = new this.BJSCANNON.Material(name);
  83341. currentMat.friction = friction;
  83342. currentMat.restitution = restitution;
  83343. this._physicsMaterials.push(currentMat);
  83344. return currentMat;
  83345. };
  83346. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83347. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83348. };
  83349. CannonJSPlugin.prototype._createShape = function (impostor) {
  83350. var object = impostor.object;
  83351. var returnValue;
  83352. var extendSize = impostor.getObjectExtendSize();
  83353. switch (impostor.type) {
  83354. case BABYLON.PhysicsImpostor.SphereImpostor:
  83355. var radiusX = extendSize.x;
  83356. var radiusY = extendSize.y;
  83357. var radiusZ = extendSize.z;
  83358. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83359. break;
  83360. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83361. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83362. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83363. break;
  83364. case BABYLON.PhysicsImpostor.BoxImpostor:
  83365. var box = extendSize.scale(0.5);
  83366. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83367. break;
  83368. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83369. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83370. returnValue = new this.BJSCANNON.Plane();
  83371. break;
  83372. case BABYLON.PhysicsImpostor.MeshImpostor:
  83373. // should transform the vertex data to world coordinates!!
  83374. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83375. var rawFaces = object.getIndices ? object.getIndices() : [];
  83376. if (!rawVerts)
  83377. return;
  83378. // get only scale! so the object could transform correctly.
  83379. var oldPosition = object.position.clone();
  83380. var oldRotation = object.rotation && object.rotation.clone();
  83381. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83382. object.position.copyFromFloats(0, 0, 0);
  83383. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83384. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83385. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83386. var transform = object.computeWorldMatrix(true);
  83387. // convert rawVerts to object space
  83388. var temp = new Array();
  83389. var index;
  83390. for (index = 0; index < rawVerts.length; index += 3) {
  83391. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83392. }
  83393. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83394. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83395. //now set back the transformation!
  83396. object.position.copyFrom(oldPosition);
  83397. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83398. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83399. break;
  83400. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83401. var oldPosition2 = object.position.clone();
  83402. var oldRotation2 = object.rotation && object.rotation.clone();
  83403. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83404. object.position.copyFromFloats(0, 0, 0);
  83405. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83406. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83407. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83408. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83409. returnValue = this._createHeightmap(object);
  83410. object.position.copyFrom(oldPosition2);
  83411. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83412. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83413. object.computeWorldMatrix(true);
  83414. break;
  83415. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83416. returnValue = new this.BJSCANNON.Particle();
  83417. break;
  83418. }
  83419. return returnValue;
  83420. };
  83421. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83422. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83423. var transform = object.computeWorldMatrix(true);
  83424. // convert rawVerts to object space
  83425. var temp = new Array();
  83426. var index;
  83427. for (index = 0; index < pos.length; index += 3) {
  83428. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83429. }
  83430. pos = temp;
  83431. var matrix = new Array();
  83432. //For now pointDepth will not be used and will be automatically calculated.
  83433. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83434. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83435. var boundingInfo = object.getBoundingInfo();
  83436. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83437. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83438. var elementSize = dim * 2 / arraySize;
  83439. for (var i = 0; i < pos.length; i = i + 3) {
  83440. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83441. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83442. var y = -pos[i + 2] + minY;
  83443. if (!matrix[x]) {
  83444. matrix[x] = [];
  83445. }
  83446. if (!matrix[x][z]) {
  83447. matrix[x][z] = y;
  83448. }
  83449. matrix[x][z] = Math.max(y, matrix[x][z]);
  83450. }
  83451. for (var x = 0; x <= arraySize; ++x) {
  83452. if (!matrix[x]) {
  83453. var loc = 1;
  83454. while (!matrix[(x + loc) % arraySize]) {
  83455. loc++;
  83456. }
  83457. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83458. //console.log("missing x", x);
  83459. }
  83460. for (var z = 0; z <= arraySize; ++z) {
  83461. if (!matrix[x][z]) {
  83462. var loc = 1;
  83463. var newValue;
  83464. while (newValue === undefined) {
  83465. newValue = matrix[x][(z + loc++) % arraySize];
  83466. }
  83467. matrix[x][z] = newValue;
  83468. }
  83469. }
  83470. }
  83471. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83472. elementSize: elementSize
  83473. });
  83474. //For future reference, needed for body transformation
  83475. shape.minY = minY;
  83476. return shape;
  83477. };
  83478. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83479. var object = impostor.object;
  83480. //make sure it is updated...
  83481. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83482. // The delta between the mesh position and the mesh bounding box center
  83483. var bInfo = object.getBoundingInfo();
  83484. if (!bInfo)
  83485. return;
  83486. var center = impostor.getObjectCenter();
  83487. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83488. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83489. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83490. this._tmpPosition.copyFrom(center);
  83491. var quaternion = object.rotationQuaternion;
  83492. if (!quaternion) {
  83493. return;
  83494. }
  83495. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83496. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83497. //-90 DEG in X, precalculated
  83498. quaternion = quaternion.multiply(this._minus90X);
  83499. //Invert! (Precalculated, 90 deg in X)
  83500. //No need to clone. this will never change.
  83501. impostor.setDeltaRotation(this._plus90X);
  83502. }
  83503. //If it is a heightfield, if should be centered.
  83504. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83505. var mesh = object;
  83506. var boundingInfo = mesh.getBoundingInfo();
  83507. //calculate the correct body position:
  83508. var rotationQuaternion = mesh.rotationQuaternion;
  83509. mesh.rotationQuaternion = this._tmpUnityRotation;
  83510. mesh.computeWorldMatrix(true);
  83511. //get original center with no rotation
  83512. var c = center.clone();
  83513. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83514. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83515. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83516. mesh.setPreTransformMatrix(p);
  83517. mesh.computeWorldMatrix(true);
  83518. //calculate the translation
  83519. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83520. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83521. //add it inverted to the delta
  83522. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83523. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83524. //rotation is back
  83525. mesh.rotationQuaternion = rotationQuaternion;
  83526. mesh.setPreTransformMatrix(oldPivot);
  83527. mesh.computeWorldMatrix(true);
  83528. }
  83529. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83530. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83531. //this._tmpPosition.copyFrom(object.position);
  83532. }
  83533. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83534. //Now update the impostor object
  83535. impostor.physicsBody.position.copy(this._tmpPosition);
  83536. impostor.physicsBody.quaternion.copy(quaternion);
  83537. };
  83538. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83539. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83540. if (impostor.object.rotationQuaternion) {
  83541. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83542. }
  83543. };
  83544. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83545. impostor.physicsBody.position.copy(newPosition);
  83546. impostor.physicsBody.quaternion.copy(newRotation);
  83547. };
  83548. CannonJSPlugin.prototype.isSupported = function () {
  83549. return this.BJSCANNON !== undefined;
  83550. };
  83551. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83552. impostor.physicsBody.velocity.copy(velocity);
  83553. };
  83554. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83555. impostor.physicsBody.angularVelocity.copy(velocity);
  83556. };
  83557. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83558. var v = impostor.physicsBody.velocity;
  83559. if (!v) {
  83560. return null;
  83561. }
  83562. return new BABYLON.Vector3(v.x, v.y, v.z);
  83563. };
  83564. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83565. var v = impostor.physicsBody.angularVelocity;
  83566. if (!v) {
  83567. return null;
  83568. }
  83569. return new BABYLON.Vector3(v.x, v.y, v.z);
  83570. };
  83571. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83572. impostor.physicsBody.mass = mass;
  83573. impostor.physicsBody.updateMassProperties();
  83574. };
  83575. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83576. return impostor.physicsBody.mass;
  83577. };
  83578. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83579. return impostor.physicsBody.material.friction;
  83580. };
  83581. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83582. impostor.physicsBody.material.friction = friction;
  83583. };
  83584. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83585. return impostor.physicsBody.material.restitution;
  83586. };
  83587. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83588. impostor.physicsBody.material.restitution = restitution;
  83589. };
  83590. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83591. impostor.physicsBody.sleep();
  83592. };
  83593. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83594. impostor.physicsBody.wakeUp();
  83595. };
  83596. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83597. joint.physicsJoint.distance = maxDistance;
  83598. };
  83599. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83600. // if (!motorIndex) {
  83601. // joint.physicsJoint.enableMotor();
  83602. // }
  83603. // }
  83604. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83605. // if (!motorIndex) {
  83606. // joint.physicsJoint.disableMotor();
  83607. // }
  83608. // }
  83609. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83610. if (!motorIndex) {
  83611. joint.physicsJoint.enableMotor();
  83612. joint.physicsJoint.setMotorSpeed(speed);
  83613. if (maxForce) {
  83614. this.setLimit(joint, maxForce);
  83615. }
  83616. }
  83617. };
  83618. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83619. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83620. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83621. };
  83622. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83623. var body = impostor.physicsBody;
  83624. mesh.position.x = body.position.x;
  83625. mesh.position.y = body.position.y;
  83626. mesh.position.z = body.position.z;
  83627. if (mesh.rotationQuaternion) {
  83628. mesh.rotationQuaternion.x = body.quaternion.x;
  83629. mesh.rotationQuaternion.y = body.quaternion.y;
  83630. mesh.rotationQuaternion.z = body.quaternion.z;
  83631. mesh.rotationQuaternion.w = body.quaternion.w;
  83632. }
  83633. };
  83634. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83635. var shape = impostor.physicsBody.shapes[0];
  83636. return shape.boundingSphereRadius;
  83637. };
  83638. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83639. var shape = impostor.physicsBody.shapes[0];
  83640. result.x = shape.halfExtents.x * 2;
  83641. result.y = shape.halfExtents.y * 2;
  83642. result.z = shape.halfExtents.z * 2;
  83643. };
  83644. CannonJSPlugin.prototype.dispose = function () {
  83645. };
  83646. CannonJSPlugin.prototype._extendNamespace = function () {
  83647. //this will force cannon to execute at least one step when using interpolation
  83648. var step_tmp1 = new this.BJSCANNON.Vec3();
  83649. var Engine = this.BJSCANNON;
  83650. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83651. maxSubSteps = maxSubSteps || 10;
  83652. timeSinceLastCalled = timeSinceLastCalled || 0;
  83653. if (timeSinceLastCalled === 0) {
  83654. this.internalStep(dt);
  83655. this.time += dt;
  83656. }
  83657. else {
  83658. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83659. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83660. var t0 = performance.now();
  83661. for (var i = 0; i !== internalSteps; i++) {
  83662. this.internalStep(dt);
  83663. if (performance.now() - t0 > dt * 1000) {
  83664. break;
  83665. }
  83666. }
  83667. this.time += timeSinceLastCalled;
  83668. var h = this.time % dt;
  83669. var h_div_dt = h / dt;
  83670. var interpvelo = step_tmp1;
  83671. var bodies = this.bodies;
  83672. for (var j = 0; j !== bodies.length; j++) {
  83673. var b = bodies[j];
  83674. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83675. b.position.vsub(b.previousPosition, interpvelo);
  83676. interpvelo.scale(h_div_dt, interpvelo);
  83677. b.position.vadd(interpvelo, b.interpolatedPosition);
  83678. }
  83679. else {
  83680. b.interpolatedPosition.copy(b.position);
  83681. b.interpolatedQuaternion.copy(b.quaternion);
  83682. }
  83683. }
  83684. }
  83685. };
  83686. };
  83687. return CannonJSPlugin;
  83688. }());
  83689. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83690. })(BABYLON || (BABYLON = {}));
  83691. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83692. var BABYLON;
  83693. (function (BABYLON) {
  83694. var OimoJSPlugin = /** @class */ (function () {
  83695. function OimoJSPlugin(iterations) {
  83696. this.name = "OimoJSPlugin";
  83697. this._tmpImpostorsArray = [];
  83698. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83699. this.BJSOIMO = OIMO;
  83700. this.world = new this.BJSOIMO.World({
  83701. iterations: iterations
  83702. });
  83703. this.world.clear();
  83704. }
  83705. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83706. this.world.gravity.copy(gravity);
  83707. };
  83708. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83709. this.world.timeStep = timeStep;
  83710. };
  83711. OimoJSPlugin.prototype.getTimeStep = function () {
  83712. return this.world.timeStep;
  83713. };
  83714. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83715. var _this = this;
  83716. impostors.forEach(function (impostor) {
  83717. impostor.beforeStep();
  83718. });
  83719. this.world.step();
  83720. impostors.forEach(function (impostor) {
  83721. impostor.afterStep();
  83722. //update the ordered impostors array
  83723. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83724. });
  83725. //check for collisions
  83726. var contact = this.world.contacts;
  83727. while (contact !== null) {
  83728. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83729. contact = contact.next;
  83730. continue;
  83731. }
  83732. //is this body colliding with any other? get the impostor
  83733. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83734. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83735. if (!mainImpostor || !collidingImpostor) {
  83736. contact = contact.next;
  83737. continue;
  83738. }
  83739. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83740. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83741. contact = contact.next;
  83742. }
  83743. };
  83744. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83745. var mass = impostor.physicsBody.mass;
  83746. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83747. };
  83748. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83749. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83750. this.applyImpulse(impostor, force, contactPoint);
  83751. };
  83752. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83753. var _this = this;
  83754. //parent-child relationship. Does this impostor has a parent impostor?
  83755. if (impostor.parent) {
  83756. if (impostor.physicsBody) {
  83757. this.removePhysicsBody(impostor);
  83758. //TODO is that needed?
  83759. impostor.forceUpdate();
  83760. }
  83761. return;
  83762. }
  83763. if (impostor.isBodyInitRequired()) {
  83764. var bodyConfig = {
  83765. name: impostor.uniqueId,
  83766. //Oimo must have mass, also for static objects.
  83767. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83768. size: [],
  83769. type: [],
  83770. pos: [],
  83771. posShape: [],
  83772. rot: [],
  83773. rotShape: [],
  83774. move: impostor.getParam("mass") !== 0,
  83775. density: impostor.getParam("mass"),
  83776. friction: impostor.getParam("friction"),
  83777. restitution: impostor.getParam("restitution"),
  83778. //Supporting older versions of Oimo
  83779. world: this.world
  83780. };
  83781. var impostors = [impostor];
  83782. var addToArray = function (parent) {
  83783. if (!parent.getChildMeshes)
  83784. return;
  83785. parent.getChildMeshes().forEach(function (m) {
  83786. if (m.physicsImpostor) {
  83787. impostors.push(m.physicsImpostor);
  83788. //m.physicsImpostor._init();
  83789. }
  83790. });
  83791. };
  83792. addToArray(impostor.object);
  83793. var checkWithEpsilon_1 = function (value) {
  83794. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83795. };
  83796. impostors.forEach(function (i) {
  83797. if (!i.object.rotationQuaternion) {
  83798. return;
  83799. }
  83800. //get the correct bounding box
  83801. var oldQuaternion = i.object.rotationQuaternion;
  83802. var rot = oldQuaternion.toEulerAngles();
  83803. var extendSize = i.getObjectExtendSize();
  83804. var radToDeg = 57.295779513082320876;
  83805. if (i === impostor) {
  83806. var center = impostor.getObjectCenter();
  83807. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83808. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83809. //Can also use Array.prototype.push.apply
  83810. bodyConfig.pos.push(center.x);
  83811. bodyConfig.pos.push(center.y);
  83812. bodyConfig.pos.push(center.z);
  83813. bodyConfig.posShape.push(0, 0, 0);
  83814. //tmp solution
  83815. bodyConfig.rot.push(rot.x * radToDeg);
  83816. bodyConfig.rot.push(rot.y * radToDeg);
  83817. bodyConfig.rot.push(rot.z * radToDeg);
  83818. bodyConfig.rotShape.push(0, 0, 0);
  83819. }
  83820. else {
  83821. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83822. bodyConfig.posShape.push(localPosition.x);
  83823. bodyConfig.posShape.push(localPosition.y);
  83824. bodyConfig.posShape.push(localPosition.z);
  83825. bodyConfig.pos.push(0, 0, 0);
  83826. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83827. bodyConfig.rot.push(0);
  83828. bodyConfig.rot.push(0);
  83829. bodyConfig.rot.push(0);
  83830. bodyConfig.rotShape.push(rot.x * radToDeg);
  83831. bodyConfig.rotShape.push(rot.y * radToDeg);
  83832. bodyConfig.rotShape.push(rot.z * radToDeg);
  83833. }
  83834. // register mesh
  83835. switch (i.type) {
  83836. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83837. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83838. case BABYLON.PhysicsImpostor.SphereImpostor:
  83839. var radiusX = extendSize.x;
  83840. var radiusY = extendSize.y;
  83841. var radiusZ = extendSize.z;
  83842. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83843. bodyConfig.type.push('sphere');
  83844. //due to the way oimo works with compounds, add 3 times
  83845. bodyConfig.size.push(size);
  83846. bodyConfig.size.push(size);
  83847. bodyConfig.size.push(size);
  83848. break;
  83849. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83850. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83851. var sizeY = checkWithEpsilon_1(extendSize.y);
  83852. bodyConfig.type.push('cylinder');
  83853. bodyConfig.size.push(sizeX);
  83854. bodyConfig.size.push(sizeY);
  83855. //due to the way oimo works with compounds, add one more value.
  83856. bodyConfig.size.push(sizeY);
  83857. break;
  83858. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83859. case BABYLON.PhysicsImpostor.BoxImpostor:
  83860. default:
  83861. var sizeX = checkWithEpsilon_1(extendSize.x);
  83862. var sizeY = checkWithEpsilon_1(extendSize.y);
  83863. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83864. bodyConfig.type.push('box');
  83865. //if (i === impostor) {
  83866. bodyConfig.size.push(sizeX);
  83867. bodyConfig.size.push(sizeY);
  83868. bodyConfig.size.push(sizeZ);
  83869. //} else {
  83870. // bodyConfig.size.push(0,0,0);
  83871. //}
  83872. break;
  83873. }
  83874. //actually not needed, but hey...
  83875. i.object.rotationQuaternion = oldQuaternion;
  83876. });
  83877. impostor.physicsBody = this.world.add(bodyConfig);
  83878. }
  83879. else {
  83880. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83881. }
  83882. impostor.setDeltaPosition(this._tmpPositionVector);
  83883. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83884. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83885. };
  83886. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83887. //impostor.physicsBody.dispose();
  83888. //Same as : (older oimo versions)
  83889. this.world.removeRigidBody(impostor.physicsBody);
  83890. };
  83891. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83892. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83893. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83894. if (!mainBody || !connectedBody) {
  83895. return;
  83896. }
  83897. var jointData = impostorJoint.joint.jointData;
  83898. var options = jointData.nativeParams || {};
  83899. var type;
  83900. var nativeJointData = {
  83901. body1: mainBody,
  83902. body2: connectedBody,
  83903. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83904. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83905. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83906. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83907. min: options.min,
  83908. max: options.max,
  83909. collision: options.collision || jointData.collision,
  83910. spring: options.spring,
  83911. //supporting older version of Oimo
  83912. world: this.world
  83913. };
  83914. switch (impostorJoint.joint.type) {
  83915. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83916. type = "jointBall";
  83917. break;
  83918. case BABYLON.PhysicsJoint.SpringJoint:
  83919. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83920. var springData = jointData;
  83921. nativeJointData.min = springData.length || nativeJointData.min;
  83922. //Max should also be set, just make sure it is at least min
  83923. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83924. case BABYLON.PhysicsJoint.DistanceJoint:
  83925. type = "jointDistance";
  83926. nativeJointData.max = jointData.maxDistance;
  83927. break;
  83928. case BABYLON.PhysicsJoint.PrismaticJoint:
  83929. type = "jointPrisme";
  83930. break;
  83931. case BABYLON.PhysicsJoint.SliderJoint:
  83932. type = "jointSlide";
  83933. break;
  83934. case BABYLON.PhysicsJoint.WheelJoint:
  83935. type = "jointWheel";
  83936. break;
  83937. case BABYLON.PhysicsJoint.HingeJoint:
  83938. default:
  83939. type = "jointHinge";
  83940. break;
  83941. }
  83942. nativeJointData.type = type;
  83943. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83944. };
  83945. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83946. //Bug in Oimo prevents us from disposing a joint in the playground
  83947. //joint.joint.physicsJoint.dispose();
  83948. //So we will bruteforce it!
  83949. try {
  83950. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83951. }
  83952. catch (e) {
  83953. BABYLON.Tools.Warn(e);
  83954. }
  83955. };
  83956. OimoJSPlugin.prototype.isSupported = function () {
  83957. return this.BJSOIMO !== undefined;
  83958. };
  83959. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83960. if (!impostor.physicsBody.sleeping) {
  83961. //TODO check that
  83962. /*if (impostor.physicsBody.shapes.next) {
  83963. var parentShape = this._getLastShape(impostor.physicsBody);
  83964. impostor.object.position.copyFrom(parentShape.position);
  83965. console.log(parentShape.position);
  83966. } else {*/
  83967. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83968. //}
  83969. if (impostor.object.rotationQuaternion) {
  83970. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83971. }
  83972. }
  83973. };
  83974. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83975. var body = impostor.physicsBody;
  83976. body.position.copy(newPosition);
  83977. body.orientation.copy(newRotation);
  83978. body.syncShapes();
  83979. body.awake();
  83980. };
  83981. /*private _getLastShape(body: any): any {
  83982. var lastShape = body.shapes;
  83983. while (lastShape.next) {
  83984. lastShape = lastShape.next;
  83985. }
  83986. return lastShape;
  83987. }*/
  83988. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83989. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83990. };
  83991. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83992. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83993. };
  83994. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83995. var v = impostor.physicsBody.linearVelocity;
  83996. if (!v) {
  83997. return null;
  83998. }
  83999. return new BABYLON.Vector3(v.x, v.y, v.z);
  84000. };
  84001. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  84002. var v = impostor.physicsBody.angularVelocity;
  84003. if (!v) {
  84004. return null;
  84005. }
  84006. return new BABYLON.Vector3(v.x, v.y, v.z);
  84007. };
  84008. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  84009. var staticBody = mass === 0;
  84010. //this will actually set the body's density and not its mass.
  84011. //But this is how oimo treats the mass variable.
  84012. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  84013. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  84014. };
  84015. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  84016. return impostor.physicsBody.shapes.density;
  84017. };
  84018. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  84019. return impostor.physicsBody.shapes.friction;
  84020. };
  84021. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  84022. impostor.physicsBody.shapes.friction = friction;
  84023. };
  84024. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84025. return impostor.physicsBody.shapes.restitution;
  84026. };
  84027. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84028. impostor.physicsBody.shapes.restitution = restitution;
  84029. };
  84030. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84031. impostor.physicsBody.sleep();
  84032. };
  84033. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84034. impostor.physicsBody.awake();
  84035. };
  84036. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84037. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84038. if (minDistance !== void 0) {
  84039. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84040. }
  84041. };
  84042. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84043. //TODO separate rotational and transational motors.
  84044. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84045. if (motor) {
  84046. motor.setMotor(speed, maxForce);
  84047. }
  84048. };
  84049. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84050. //TODO separate rotational and transational motors.
  84051. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84052. if (motor) {
  84053. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84054. }
  84055. };
  84056. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84057. var body = impostor.physicsBody;
  84058. mesh.position.x = body.position.x;
  84059. mesh.position.y = body.position.y;
  84060. mesh.position.z = body.position.z;
  84061. if (mesh.rotationQuaternion) {
  84062. mesh.rotationQuaternion.x = body.orientation.x;
  84063. mesh.rotationQuaternion.y = body.orientation.y;
  84064. mesh.rotationQuaternion.z = body.orientation.z;
  84065. mesh.rotationQuaternion.w = body.orientation.s;
  84066. }
  84067. };
  84068. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84069. return impostor.physicsBody.shapes.radius;
  84070. };
  84071. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84072. var shape = impostor.physicsBody.shapes;
  84073. result.x = shape.halfWidth * 2;
  84074. result.y = shape.halfHeight * 2;
  84075. result.z = shape.halfDepth * 2;
  84076. };
  84077. OimoJSPlugin.prototype.dispose = function () {
  84078. this.world.clear();
  84079. };
  84080. return OimoJSPlugin;
  84081. }());
  84082. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84083. })(BABYLON || (BABYLON = {}));
  84084. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84085. var BABYLON;
  84086. (function (BABYLON) {
  84087. /*
  84088. * Based on jsTGALoader - Javascript loader for TGA file
  84089. * By Vincent Thibault
  84090. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84091. */
  84092. var TGATools = /** @class */ (function () {
  84093. function TGATools() {
  84094. }
  84095. TGATools.GetTGAHeader = function (data) {
  84096. var offset = 0;
  84097. var header = {
  84098. id_length: data[offset++],
  84099. colormap_type: data[offset++],
  84100. image_type: data[offset++],
  84101. colormap_index: data[offset++] | data[offset++] << 8,
  84102. colormap_length: data[offset++] | data[offset++] << 8,
  84103. colormap_size: data[offset++],
  84104. origin: [
  84105. data[offset++] | data[offset++] << 8,
  84106. data[offset++] | data[offset++] << 8
  84107. ],
  84108. width: data[offset++] | data[offset++] << 8,
  84109. height: data[offset++] | data[offset++] << 8,
  84110. pixel_size: data[offset++],
  84111. flags: data[offset++]
  84112. };
  84113. return header;
  84114. };
  84115. TGATools.UploadContent = function (gl, data) {
  84116. // Not enough data to contain header ?
  84117. if (data.length < 19) {
  84118. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84119. return;
  84120. }
  84121. // Read Header
  84122. var offset = 18;
  84123. var header = TGATools.GetTGAHeader(data);
  84124. // Assume it's a valid Targa file.
  84125. if (header.id_length + offset > data.length) {
  84126. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84127. return;
  84128. }
  84129. // Skip not needed data
  84130. offset += header.id_length;
  84131. var use_rle = false;
  84132. var use_pal = false;
  84133. var use_grey = false;
  84134. // Get some informations.
  84135. switch (header.image_type) {
  84136. case TGATools._TYPE_RLE_INDEXED:
  84137. use_rle = true;
  84138. case TGATools._TYPE_INDEXED:
  84139. use_pal = true;
  84140. break;
  84141. case TGATools._TYPE_RLE_RGB:
  84142. use_rle = true;
  84143. case TGATools._TYPE_RGB:
  84144. // use_rgb = true;
  84145. break;
  84146. case TGATools._TYPE_RLE_GREY:
  84147. use_rle = true;
  84148. case TGATools._TYPE_GREY:
  84149. use_grey = true;
  84150. break;
  84151. }
  84152. var pixel_data;
  84153. // var numAlphaBits = header.flags & 0xf;
  84154. var pixel_size = header.pixel_size >> 3;
  84155. var pixel_total = header.width * header.height * pixel_size;
  84156. // Read palettes
  84157. var palettes;
  84158. if (use_pal) {
  84159. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84160. }
  84161. // Read LRE
  84162. if (use_rle) {
  84163. pixel_data = new Uint8Array(pixel_total);
  84164. var c, count, i;
  84165. var localOffset = 0;
  84166. var pixels = new Uint8Array(pixel_size);
  84167. while (offset < pixel_total && localOffset < pixel_total) {
  84168. c = data[offset++];
  84169. count = (c & 0x7f) + 1;
  84170. // RLE pixels
  84171. if (c & 0x80) {
  84172. // Bind pixel tmp array
  84173. for (i = 0; i < pixel_size; ++i) {
  84174. pixels[i] = data[offset++];
  84175. }
  84176. // Copy pixel array
  84177. for (i = 0; i < count; ++i) {
  84178. pixel_data.set(pixels, localOffset + i * pixel_size);
  84179. }
  84180. localOffset += pixel_size * count;
  84181. }
  84182. // Raw pixels
  84183. else {
  84184. count *= pixel_size;
  84185. for (i = 0; i < count; ++i) {
  84186. pixel_data[localOffset + i] = data[offset++];
  84187. }
  84188. localOffset += count;
  84189. }
  84190. }
  84191. }
  84192. // RAW Pixels
  84193. else {
  84194. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84195. }
  84196. // Load to texture
  84197. var x_start, y_start, x_step, y_step, y_end, x_end;
  84198. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84199. default:
  84200. case TGATools._ORIGIN_UL:
  84201. x_start = 0;
  84202. x_step = 1;
  84203. x_end = header.width;
  84204. y_start = 0;
  84205. y_step = 1;
  84206. y_end = header.height;
  84207. break;
  84208. case TGATools._ORIGIN_BL:
  84209. x_start = 0;
  84210. x_step = 1;
  84211. x_end = header.width;
  84212. y_start = header.height - 1;
  84213. y_step = -1;
  84214. y_end = -1;
  84215. break;
  84216. case TGATools._ORIGIN_UR:
  84217. x_start = header.width - 1;
  84218. x_step = -1;
  84219. x_end = -1;
  84220. y_start = 0;
  84221. y_step = 1;
  84222. y_end = header.height;
  84223. break;
  84224. case TGATools._ORIGIN_BR:
  84225. x_start = header.width - 1;
  84226. x_step = -1;
  84227. x_end = -1;
  84228. y_start = header.height - 1;
  84229. y_step = -1;
  84230. y_end = -1;
  84231. break;
  84232. }
  84233. // Load the specify method
  84234. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84235. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84236. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84237. };
  84238. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84239. var image = pixel_data, colormap = palettes;
  84240. var width = header.width, height = header.height;
  84241. var color, i = 0, x, y;
  84242. var imageData = new Uint8Array(width * height * 4);
  84243. for (y = y_start; y !== y_end; y += y_step) {
  84244. for (x = x_start; x !== x_end; x += x_step, i++) {
  84245. color = image[i];
  84246. imageData[(x + width * y) * 4 + 3] = 255;
  84247. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84248. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84249. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84250. }
  84251. }
  84252. return imageData;
  84253. };
  84254. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84255. var image = pixel_data;
  84256. var width = header.width, height = header.height;
  84257. var color, i = 0, x, y;
  84258. var imageData = new Uint8Array(width * height * 4);
  84259. for (y = y_start; y !== y_end; y += y_step) {
  84260. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84261. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84262. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84263. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84264. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84265. imageData[(x + width * y) * 4 + 0] = r;
  84266. imageData[(x + width * y) * 4 + 1] = g;
  84267. imageData[(x + width * y) * 4 + 2] = b;
  84268. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84269. }
  84270. }
  84271. return imageData;
  84272. };
  84273. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84274. var image = pixel_data;
  84275. var width = header.width, height = header.height;
  84276. var i = 0, x, y;
  84277. var imageData = new Uint8Array(width * height * 4);
  84278. for (y = y_start; y !== y_end; y += y_step) {
  84279. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84280. imageData[(x + width * y) * 4 + 3] = 255;
  84281. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84282. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84283. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84284. }
  84285. }
  84286. return imageData;
  84287. };
  84288. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84289. var image = pixel_data;
  84290. var width = header.width, height = header.height;
  84291. var i = 0, x, y;
  84292. var imageData = new Uint8Array(width * height * 4);
  84293. for (y = y_start; y !== y_end; y += y_step) {
  84294. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84295. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84296. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84297. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84298. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84299. }
  84300. }
  84301. return imageData;
  84302. };
  84303. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84304. var image = pixel_data;
  84305. var width = header.width, height = header.height;
  84306. var color, i = 0, x, y;
  84307. var imageData = new Uint8Array(width * height * 4);
  84308. for (y = y_start; y !== y_end; y += y_step) {
  84309. for (x = x_start; x !== x_end; x += x_step, i++) {
  84310. color = image[i];
  84311. imageData[(x + width * y) * 4 + 0] = color;
  84312. imageData[(x + width * y) * 4 + 1] = color;
  84313. imageData[(x + width * y) * 4 + 2] = color;
  84314. imageData[(x + width * y) * 4 + 3] = 255;
  84315. }
  84316. }
  84317. return imageData;
  84318. };
  84319. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84320. var image = pixel_data;
  84321. var width = header.width, height = header.height;
  84322. var i = 0, x, y;
  84323. var imageData = new Uint8Array(width * height * 4);
  84324. for (y = y_start; y !== y_end; y += y_step) {
  84325. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84326. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84327. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84328. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84329. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84330. }
  84331. }
  84332. return imageData;
  84333. };
  84334. //private static _TYPE_NO_DATA = 0;
  84335. TGATools._TYPE_INDEXED = 1;
  84336. TGATools._TYPE_RGB = 2;
  84337. TGATools._TYPE_GREY = 3;
  84338. TGATools._TYPE_RLE_INDEXED = 9;
  84339. TGATools._TYPE_RLE_RGB = 10;
  84340. TGATools._TYPE_RLE_GREY = 11;
  84341. TGATools._ORIGIN_MASK = 0x30;
  84342. TGATools._ORIGIN_SHIFT = 0x04;
  84343. TGATools._ORIGIN_BL = 0x00;
  84344. TGATools._ORIGIN_BR = 0x01;
  84345. TGATools._ORIGIN_UL = 0x02;
  84346. TGATools._ORIGIN_UR = 0x03;
  84347. return TGATools;
  84348. }());
  84349. BABYLON.TGATools = TGATools;
  84350. })(BABYLON || (BABYLON = {}));
  84351. //# sourceMappingURL=babylon.tga.js.map
  84352. var BABYLON;
  84353. (function (BABYLON) {
  84354. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84355. // All values and structures referenced from:
  84356. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84357. var DDS_MAGIC = 0x20534444;
  84358. var
  84359. //DDSD_CAPS = 0x1,
  84360. //DDSD_HEIGHT = 0x2,
  84361. //DDSD_WIDTH = 0x4,
  84362. //DDSD_PITCH = 0x8,
  84363. //DDSD_PIXELFORMAT = 0x1000,
  84364. DDSD_MIPMAPCOUNT = 0x20000;
  84365. //DDSD_LINEARSIZE = 0x80000,
  84366. //DDSD_DEPTH = 0x800000;
  84367. // var DDSCAPS_COMPLEX = 0x8,
  84368. // DDSCAPS_MIPMAP = 0x400000,
  84369. // DDSCAPS_TEXTURE = 0x1000;
  84370. var DDSCAPS2_CUBEMAP = 0x200;
  84371. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84372. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84373. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84374. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84375. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84376. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84377. // DDSCAPS2_VOLUME = 0x200000;
  84378. var
  84379. //DDPF_ALPHAPIXELS = 0x1,
  84380. //DDPF_ALPHA = 0x2,
  84381. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84382. //DDPF_YUV = 0x200,
  84383. DDPF_LUMINANCE = 0x20000;
  84384. function FourCCToInt32(value) {
  84385. return value.charCodeAt(0) +
  84386. (value.charCodeAt(1) << 8) +
  84387. (value.charCodeAt(2) << 16) +
  84388. (value.charCodeAt(3) << 24);
  84389. }
  84390. function Int32ToFourCC(value) {
  84391. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84392. }
  84393. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84394. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84395. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84396. var FOURCC_DX10 = FourCCToInt32("DX10");
  84397. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84398. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84399. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84400. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84401. var headerLengthInt = 31; // The header length in 32 bit ints
  84402. // Offsets into the header array
  84403. var off_magic = 0;
  84404. var off_size = 1;
  84405. var off_flags = 2;
  84406. var off_height = 3;
  84407. var off_width = 4;
  84408. var off_mipmapCount = 7;
  84409. var off_pfFlags = 20;
  84410. var off_pfFourCC = 21;
  84411. var off_RGBbpp = 22;
  84412. var off_RMask = 23;
  84413. var off_GMask = 24;
  84414. var off_BMask = 25;
  84415. var off_AMask = 26;
  84416. // var off_caps1 = 27;
  84417. var off_caps2 = 28;
  84418. // var off_caps3 = 29;
  84419. // var off_caps4 = 30;
  84420. var off_dxgiFormat = 32;
  84421. ;
  84422. var DDSTools = /** @class */ (function () {
  84423. function DDSTools() {
  84424. }
  84425. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84426. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84427. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84428. var mipmapCount = 1;
  84429. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84430. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84431. }
  84432. var fourCC = header[off_pfFourCC];
  84433. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84434. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84435. switch (fourCC) {
  84436. case FOURCC_D3DFMT_R16G16B16A16F:
  84437. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84438. break;
  84439. case FOURCC_D3DFMT_R32G32B32A32F:
  84440. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84441. break;
  84442. case FOURCC_DX10:
  84443. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84444. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84445. break;
  84446. }
  84447. }
  84448. return {
  84449. width: header[off_width],
  84450. height: header[off_height],
  84451. mipmapCount: mipmapCount,
  84452. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84453. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84454. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84455. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84456. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84457. dxgiFormat: dxgiFormat,
  84458. textureType: textureType
  84459. };
  84460. };
  84461. DDSTools._ToHalfFloat = function (value) {
  84462. if (!DDSTools._FloatView) {
  84463. DDSTools._FloatView = new Float32Array(1);
  84464. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84465. }
  84466. DDSTools._FloatView[0] = value;
  84467. var x = DDSTools._Int32View[0];
  84468. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84469. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84470. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84471. /* If zero, or denormal, or exponent underflows too much for a denormal
  84472. * half, return signed zero. */
  84473. if (e < 103) {
  84474. return bits;
  84475. }
  84476. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84477. if (e > 142) {
  84478. bits |= 0x7c00;
  84479. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84480. * not Inf, so make sure we set one mantissa bit too. */
  84481. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84482. return bits;
  84483. }
  84484. /* If exponent underflows but not too much, return a denormal */
  84485. if (e < 113) {
  84486. m |= 0x0800;
  84487. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84488. * to 1, which is OK. */
  84489. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84490. return bits;
  84491. }
  84492. bits |= ((e - 112) << 10) | (m >> 1);
  84493. bits += m & 1;
  84494. return bits;
  84495. };
  84496. DDSTools._FromHalfFloat = function (value) {
  84497. var s = (value & 0x8000) >> 15;
  84498. var e = (value & 0x7C00) >> 10;
  84499. var f = value & 0x03FF;
  84500. if (e === 0) {
  84501. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84502. }
  84503. else if (e == 0x1F) {
  84504. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84505. }
  84506. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84507. };
  84508. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84509. var destArray = new Float32Array(dataLength);
  84510. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84511. var index = 0;
  84512. for (var y = 0; y < height; y++) {
  84513. for (var x = 0; x < width; x++) {
  84514. var srcPos = (x + y * width) * 4;
  84515. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84516. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84517. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84518. if (DDSTools.StoreLODInAlphaChannel) {
  84519. destArray[index + 3] = lod;
  84520. }
  84521. else {
  84522. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84523. }
  84524. index += 4;
  84525. }
  84526. }
  84527. return destArray;
  84528. };
  84529. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84530. if (DDSTools.StoreLODInAlphaChannel) {
  84531. var destArray = new Uint16Array(dataLength);
  84532. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84533. var index = 0;
  84534. for (var y = 0; y < height; y++) {
  84535. for (var x = 0; x < width; x++) {
  84536. var srcPos = (x + y * width) * 4;
  84537. destArray[index] = srcData[srcPos];
  84538. destArray[index + 1] = srcData[srcPos + 1];
  84539. destArray[index + 2] = srcData[srcPos + 2];
  84540. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84541. index += 4;
  84542. }
  84543. }
  84544. return destArray;
  84545. }
  84546. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84547. };
  84548. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84549. if (DDSTools.StoreLODInAlphaChannel) {
  84550. var destArray = new Float32Array(dataLength);
  84551. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84552. var index = 0;
  84553. for (var y = 0; y < height; y++) {
  84554. for (var x = 0; x < width; x++) {
  84555. var srcPos = (x + y * width) * 4;
  84556. destArray[index] = srcData[srcPos];
  84557. destArray[index + 1] = srcData[srcPos + 1];
  84558. destArray[index + 2] = srcData[srcPos + 2];
  84559. destArray[index + 3] = lod;
  84560. index += 4;
  84561. }
  84562. }
  84563. return destArray;
  84564. }
  84565. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84566. };
  84567. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84568. var destArray = new Uint8Array(dataLength);
  84569. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84570. var index = 0;
  84571. for (var y = 0; y < height; y++) {
  84572. for (var x = 0; x < width; x++) {
  84573. var srcPos = (x + y * width) * 4;
  84574. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84575. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84576. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84577. if (DDSTools.StoreLODInAlphaChannel) {
  84578. destArray[index + 3] = lod;
  84579. }
  84580. else {
  84581. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84582. }
  84583. index += 4;
  84584. }
  84585. }
  84586. return destArray;
  84587. };
  84588. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84589. var destArray = new Uint8Array(dataLength);
  84590. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84591. var index = 0;
  84592. for (var y = 0; y < height; y++) {
  84593. for (var x = 0; x < width; x++) {
  84594. var srcPos = (x + y * width) * 4;
  84595. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84596. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84597. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84598. if (DDSTools.StoreLODInAlphaChannel) {
  84599. destArray[index + 3] = lod;
  84600. }
  84601. else {
  84602. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84603. }
  84604. index += 4;
  84605. }
  84606. }
  84607. return destArray;
  84608. };
  84609. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84610. var byteArray = new Uint8Array(dataLength);
  84611. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84612. var index = 0;
  84613. for (var y = 0; y < height; y++) {
  84614. for (var x = 0; x < width; x++) {
  84615. var srcPos = (x + y * width) * 4;
  84616. byteArray[index] = srcData[srcPos + rOffset];
  84617. byteArray[index + 1] = srcData[srcPos + gOffset];
  84618. byteArray[index + 2] = srcData[srcPos + bOffset];
  84619. byteArray[index + 3] = srcData[srcPos + aOffset];
  84620. index += 4;
  84621. }
  84622. }
  84623. return byteArray;
  84624. };
  84625. DDSTools._ExtractLongWordOrder = function (value) {
  84626. if (value === 0 || value === 255 || value === -16777216) {
  84627. return 0;
  84628. }
  84629. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84630. };
  84631. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84632. var byteArray = new Uint8Array(dataLength);
  84633. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84634. var index = 0;
  84635. for (var y = 0; y < height; y++) {
  84636. for (var x = 0; x < width; x++) {
  84637. var srcPos = (x + y * width) * 3;
  84638. byteArray[index] = srcData[srcPos + rOffset];
  84639. byteArray[index + 1] = srcData[srcPos + gOffset];
  84640. byteArray[index + 2] = srcData[srcPos + bOffset];
  84641. index += 3;
  84642. }
  84643. }
  84644. return byteArray;
  84645. };
  84646. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84647. var byteArray = new Uint8Array(dataLength);
  84648. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84649. var index = 0;
  84650. for (var y = 0; y < height; y++) {
  84651. for (var x = 0; x < width; x++) {
  84652. var srcPos = (x + y * width);
  84653. byteArray[index] = srcData[srcPos];
  84654. index++;
  84655. }
  84656. }
  84657. return byteArray;
  84658. };
  84659. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84660. if (lodIndex === void 0) { lodIndex = -1; }
  84661. var sphericalPolynomialFaces = null;
  84662. if (info.sphericalPolynomial) {
  84663. sphericalPolynomialFaces = new Array();
  84664. }
  84665. var ext = engine.getCaps().s3tc;
  84666. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84667. var fourCC, width, height, dataLength = 0, dataOffset;
  84668. var byteArray, mipmapCount, mip;
  84669. var internalFormat = 0;
  84670. var format = 0;
  84671. var blockBytes = 1;
  84672. if (header[off_magic] !== DDS_MAGIC) {
  84673. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84674. return;
  84675. }
  84676. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84677. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84678. return;
  84679. }
  84680. if (info.isCompressed && !ext) {
  84681. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84682. return;
  84683. }
  84684. var bpp = header[off_RGBbpp];
  84685. dataOffset = header[off_size] + 4;
  84686. var computeFormats = false;
  84687. if (info.isFourCC) {
  84688. fourCC = header[off_pfFourCC];
  84689. switch (fourCC) {
  84690. case FOURCC_DXT1:
  84691. blockBytes = 8;
  84692. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84693. break;
  84694. case FOURCC_DXT3:
  84695. blockBytes = 16;
  84696. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84697. break;
  84698. case FOURCC_DXT5:
  84699. blockBytes = 16;
  84700. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84701. break;
  84702. case FOURCC_D3DFMT_R16G16B16A16F:
  84703. computeFormats = true;
  84704. break;
  84705. case FOURCC_D3DFMT_R32G32B32A32F:
  84706. computeFormats = true;
  84707. break;
  84708. case FOURCC_DX10:
  84709. // There is an additionnal header so dataOffset need to be changed
  84710. dataOffset += 5 * 4; // 5 uints
  84711. var supported = false;
  84712. switch (info.dxgiFormat) {
  84713. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84714. computeFormats = true;
  84715. supported = true;
  84716. break;
  84717. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84718. info.isRGB = true;
  84719. info.isFourCC = false;
  84720. bpp = 32;
  84721. supported = true;
  84722. break;
  84723. }
  84724. if (supported) {
  84725. break;
  84726. }
  84727. default:
  84728. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84729. return;
  84730. }
  84731. }
  84732. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84733. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84734. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84735. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84736. if (computeFormats) {
  84737. format = engine._getWebGLTextureType(info.textureType);
  84738. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84739. }
  84740. mipmapCount = 1;
  84741. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84742. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84743. }
  84744. for (var face = 0; face < faces; face++) {
  84745. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84746. width = header[off_width];
  84747. height = header[off_height];
  84748. for (mip = 0; mip < mipmapCount; ++mip) {
  84749. if (lodIndex === -1 || lodIndex === mip) {
  84750. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84751. var i = (lodIndex === -1) ? mip : 0;
  84752. if (!info.isCompressed && info.isFourCC) {
  84753. dataLength = width * height * 4;
  84754. var floatArray = null;
  84755. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84756. if (bpp === 128) {
  84757. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84758. if (sphericalPolynomialFaces && i == 0) {
  84759. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84760. }
  84761. }
  84762. else if (bpp === 64) {
  84763. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84764. if (sphericalPolynomialFaces && i == 0) {
  84765. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84766. }
  84767. }
  84768. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84769. format = engine._getWebGLTextureType(info.textureType);
  84770. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84771. }
  84772. else {
  84773. if (bpp === 128) {
  84774. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84775. if (sphericalPolynomialFaces && i == 0) {
  84776. sphericalPolynomialFaces.push(floatArray);
  84777. }
  84778. }
  84779. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84780. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84781. if (sphericalPolynomialFaces && i == 0) {
  84782. sphericalPolynomialFaces.push(floatArray);
  84783. }
  84784. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84785. format = engine._getWebGLTextureType(info.textureType);
  84786. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84787. }
  84788. else { // 64
  84789. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84790. if (sphericalPolynomialFaces && i == 0) {
  84791. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84792. }
  84793. }
  84794. }
  84795. if (floatArray) {
  84796. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84797. }
  84798. }
  84799. else if (info.isRGB) {
  84800. if (bpp === 24) {
  84801. dataLength = width * height * 3;
  84802. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84803. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84804. }
  84805. else { // 32
  84806. dataLength = width * height * 4;
  84807. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84808. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84809. }
  84810. }
  84811. else if (info.isLuminance) {
  84812. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84813. var unpaddedRowSize = width;
  84814. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84815. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84816. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84817. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84818. }
  84819. else {
  84820. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84821. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84822. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84823. }
  84824. }
  84825. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84826. width *= 0.5;
  84827. height *= 0.5;
  84828. width = Math.max(1.0, width);
  84829. height = Math.max(1.0, height);
  84830. }
  84831. if (currentFace !== undefined) {
  84832. // Loading a single face
  84833. break;
  84834. }
  84835. }
  84836. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84837. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84838. size: header[off_width],
  84839. right: sphericalPolynomialFaces[0],
  84840. left: sphericalPolynomialFaces[1],
  84841. up: sphericalPolynomialFaces[2],
  84842. down: sphericalPolynomialFaces[3],
  84843. front: sphericalPolynomialFaces[4],
  84844. back: sphericalPolynomialFaces[5],
  84845. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84846. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84847. gammaSpace: false,
  84848. });
  84849. }
  84850. else {
  84851. info.sphericalPolynomial = undefined;
  84852. }
  84853. };
  84854. DDSTools.StoreLODInAlphaChannel = false;
  84855. return DDSTools;
  84856. }());
  84857. BABYLON.DDSTools = DDSTools;
  84858. })(BABYLON || (BABYLON = {}));
  84859. //# sourceMappingURL=babylon.dds.js.map
  84860. var BABYLON;
  84861. (function (BABYLON) {
  84862. /**
  84863. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84864. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84865. */
  84866. var KhronosTextureContainer = /** @class */ (function () {
  84867. /**
  84868. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84869. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84870. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84871. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84872. */
  84873. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84874. this.arrayBuffer = arrayBuffer;
  84875. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84876. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84877. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84878. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84879. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84880. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84881. BABYLON.Tools.Error("texture missing KTX identifier");
  84882. return;
  84883. }
  84884. // load the reset of the header in native 32 bit int
  84885. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84886. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84887. var oppositeEndianess = header[0] === 0x01020304;
  84888. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84889. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84890. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84891. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84892. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84893. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84894. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84895. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84896. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84897. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84898. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84899. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84900. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84901. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84902. if (this.glType !== 0) {
  84903. BABYLON.Tools.Error("only compressed formats currently supported");
  84904. return;
  84905. }
  84906. else {
  84907. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84908. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84909. }
  84910. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84911. BABYLON.Tools.Error("only 2D textures currently supported");
  84912. return;
  84913. }
  84914. if (this.numberOfArrayElements !== 0) {
  84915. BABYLON.Tools.Error("texture arrays not currently supported");
  84916. return;
  84917. }
  84918. if (this.numberOfFaces !== facesExpected) {
  84919. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84920. return;
  84921. }
  84922. // we now have a completely validated file, so could use existence of loadType as success
  84923. // would need to make this more elaborate & adjust checks above to support more than one load type
  84924. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84925. }
  84926. // not as fast hardware based, but will probably never need to use
  84927. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84928. return ((val & 0xFF) << 24)
  84929. | ((val & 0xFF00) << 8)
  84930. | ((val >> 8) & 0xFF00)
  84931. | ((val >> 24) & 0xFF);
  84932. };
  84933. /**
  84934. * It is assumed that the texture has already been created & is currently bound
  84935. */
  84936. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84937. switch (this.loadType) {
  84938. case KhronosTextureContainer.COMPRESSED_2D:
  84939. this._upload2DCompressedLevels(gl, loadMipmaps);
  84940. break;
  84941. case KhronosTextureContainer.TEX_2D:
  84942. case KhronosTextureContainer.COMPRESSED_3D:
  84943. case KhronosTextureContainer.TEX_3D:
  84944. }
  84945. };
  84946. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84947. // initialize width & height for level 1
  84948. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84949. var width = this.pixelWidth;
  84950. var height = this.pixelHeight;
  84951. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84952. for (var level = 0; level < mipmapCount; level++) {
  84953. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84954. for (var face = 0; face < this.numberOfFaces; face++) {
  84955. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84956. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84957. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84958. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84959. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84960. }
  84961. width = Math.max(1.0, width * 0.5);
  84962. height = Math.max(1.0, height * 0.5);
  84963. }
  84964. };
  84965. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84966. // load types
  84967. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84968. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84969. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84970. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84971. return KhronosTextureContainer;
  84972. }());
  84973. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84974. })(BABYLON || (BABYLON = {}));
  84975. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84976. var BABYLON;
  84977. (function (BABYLON) {
  84978. var Debug;
  84979. (function (Debug) {
  84980. /**
  84981. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84982. */
  84983. var SkeletonViewer = /** @class */ (function () {
  84984. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84985. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84986. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84987. this.skeleton = skeleton;
  84988. this.mesh = mesh;
  84989. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84990. this.renderingGroupId = renderingGroupId;
  84991. this.color = BABYLON.Color3.White();
  84992. this._debugLines = new Array();
  84993. this._isEnabled = false;
  84994. this._scene = scene;
  84995. this.update();
  84996. this._renderFunction = this.update.bind(this);
  84997. }
  84998. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84999. get: function () {
  85000. return this._isEnabled;
  85001. },
  85002. set: function (value) {
  85003. if (this._isEnabled === value) {
  85004. return;
  85005. }
  85006. this._isEnabled = value;
  85007. if (value) {
  85008. this._scene.registerBeforeRender(this._renderFunction);
  85009. }
  85010. else {
  85011. this._scene.unregisterBeforeRender(this._renderFunction);
  85012. }
  85013. },
  85014. enumerable: true,
  85015. configurable: true
  85016. });
  85017. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  85018. if (x === void 0) { x = 0; }
  85019. if (y === void 0) { y = 0; }
  85020. if (z === void 0) { z = 0; }
  85021. var tmat = BABYLON.Tmp.Matrix[0];
  85022. var parentBone = bone.getParent();
  85023. tmat.copyFrom(bone.getLocalMatrix());
  85024. if (x !== 0 || y !== 0 || z !== 0) {
  85025. var tmat2 = BABYLON.Tmp.Matrix[1];
  85026. BABYLON.Matrix.IdentityToRef(tmat2);
  85027. tmat2.m[12] = x;
  85028. tmat2.m[13] = y;
  85029. tmat2.m[14] = z;
  85030. tmat2.multiplyToRef(tmat, tmat);
  85031. }
  85032. if (parentBone) {
  85033. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85034. }
  85035. tmat.multiplyToRef(meshMat, tmat);
  85036. position.x = tmat.m[12];
  85037. position.y = tmat.m[13];
  85038. position.z = tmat.m[14];
  85039. };
  85040. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85041. var len = bones.length;
  85042. var meshPos = this.mesh.position;
  85043. for (var i = 0; i < len; i++) {
  85044. var bone = bones[i];
  85045. var points = this._debugLines[i];
  85046. if (!points) {
  85047. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85048. this._debugLines[i] = points;
  85049. }
  85050. this._getBonePosition(points[0], bone, meshMat);
  85051. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85052. points[0].subtractInPlace(meshPos);
  85053. points[1].subtractInPlace(meshPos);
  85054. }
  85055. };
  85056. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85057. var len = bones.length;
  85058. var boneNum = 0;
  85059. var meshPos = this.mesh.position;
  85060. for (var i = len - 1; i >= 0; i--) {
  85061. var childBone = bones[i];
  85062. var parentBone = childBone.getParent();
  85063. if (!parentBone) {
  85064. continue;
  85065. }
  85066. var points = this._debugLines[boneNum];
  85067. if (!points) {
  85068. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85069. this._debugLines[boneNum] = points;
  85070. }
  85071. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85072. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85073. points[0].subtractInPlace(meshPos);
  85074. points[1].subtractInPlace(meshPos);
  85075. boneNum++;
  85076. }
  85077. };
  85078. SkeletonViewer.prototype.update = function () {
  85079. if (this.autoUpdateBonesMatrices) {
  85080. this.skeleton.computeAbsoluteTransforms();
  85081. }
  85082. if (this.skeleton.bones[0].length === undefined) {
  85083. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85084. }
  85085. else {
  85086. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85087. }
  85088. if (!this._debugMesh) {
  85089. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85090. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85091. }
  85092. else {
  85093. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85094. }
  85095. this._debugMesh.position.copyFrom(this.mesh.position);
  85096. this._debugMesh.color = this.color;
  85097. };
  85098. SkeletonViewer.prototype.dispose = function () {
  85099. if (this._debugMesh) {
  85100. this.isEnabled = false;
  85101. this._debugMesh.dispose();
  85102. this._debugMesh = null;
  85103. }
  85104. };
  85105. return SkeletonViewer;
  85106. }());
  85107. Debug.SkeletonViewer = SkeletonViewer;
  85108. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85109. })(BABYLON || (BABYLON = {}));
  85110. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85111. /**
  85112. * Module Debug contains the (visual) components to debug a scene correctly
  85113. */
  85114. var BABYLON;
  85115. (function (BABYLON) {
  85116. var Debug;
  85117. (function (Debug) {
  85118. /**
  85119. * The Axes viewer will show 3 axes in a specific point in space
  85120. */
  85121. var AxesViewer = /** @class */ (function () {
  85122. function AxesViewer(scene, scaleLines) {
  85123. if (scaleLines === void 0) { scaleLines = 1; }
  85124. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85125. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85126. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85127. this.scaleLines = 1;
  85128. this.scaleLines = scaleLines;
  85129. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85130. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85131. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85132. this._xmesh.renderingGroupId = 2;
  85133. this._ymesh.renderingGroupId = 2;
  85134. this._zmesh.renderingGroupId = 2;
  85135. this._xmesh.material.checkReadyOnlyOnce = true;
  85136. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85137. this._ymesh.material.checkReadyOnlyOnce = true;
  85138. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85139. this._zmesh.material.checkReadyOnlyOnce = true;
  85140. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85141. this.scene = scene;
  85142. }
  85143. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85144. var scaleLines = this.scaleLines;
  85145. if (this._xmesh) {
  85146. this._xmesh.position.copyFrom(position);
  85147. }
  85148. if (this._ymesh) {
  85149. this._ymesh.position.copyFrom(position);
  85150. }
  85151. if (this._zmesh) {
  85152. this._zmesh.position.copyFrom(position);
  85153. }
  85154. var point2 = this._xline[1];
  85155. point2.x = xaxis.x * scaleLines;
  85156. point2.y = xaxis.y * scaleLines;
  85157. point2.z = xaxis.z * scaleLines;
  85158. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85159. point2 = this._yline[1];
  85160. point2.x = yaxis.x * scaleLines;
  85161. point2.y = yaxis.y * scaleLines;
  85162. point2.z = yaxis.z * scaleLines;
  85163. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85164. point2 = this._zline[1];
  85165. point2.x = zaxis.x * scaleLines;
  85166. point2.y = zaxis.y * scaleLines;
  85167. point2.z = zaxis.z * scaleLines;
  85168. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85169. };
  85170. AxesViewer.prototype.dispose = function () {
  85171. if (this._xmesh) {
  85172. this._xmesh.dispose();
  85173. }
  85174. if (this._ymesh) {
  85175. this._ymesh.dispose();
  85176. }
  85177. if (this._zmesh) {
  85178. this._zmesh.dispose();
  85179. }
  85180. this._xmesh = null;
  85181. this._ymesh = null;
  85182. this._zmesh = null;
  85183. this.scene = null;
  85184. };
  85185. return AxesViewer;
  85186. }());
  85187. Debug.AxesViewer = AxesViewer;
  85188. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85189. })(BABYLON || (BABYLON = {}));
  85190. //# sourceMappingURL=babylon.axesViewer.js.map
  85191. var BABYLON;
  85192. (function (BABYLON) {
  85193. var Debug;
  85194. (function (Debug) {
  85195. /**
  85196. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85197. */
  85198. var BoneAxesViewer = /** @class */ (function (_super) {
  85199. __extends(BoneAxesViewer, _super);
  85200. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85201. if (scaleLines === void 0) { scaleLines = 1; }
  85202. var _this = _super.call(this, scene, scaleLines) || this;
  85203. _this.pos = BABYLON.Vector3.Zero();
  85204. _this.xaxis = BABYLON.Vector3.Zero();
  85205. _this.yaxis = BABYLON.Vector3.Zero();
  85206. _this.zaxis = BABYLON.Vector3.Zero();
  85207. _this.mesh = mesh;
  85208. _this.bone = bone;
  85209. return _this;
  85210. }
  85211. BoneAxesViewer.prototype.update = function () {
  85212. if (!this.mesh || !this.bone) {
  85213. return;
  85214. }
  85215. var bone = this.bone;
  85216. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85217. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85218. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85219. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85220. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85221. };
  85222. BoneAxesViewer.prototype.dispose = function () {
  85223. if (this.mesh) {
  85224. this.mesh = null;
  85225. this.bone = null;
  85226. _super.prototype.dispose.call(this);
  85227. }
  85228. };
  85229. return BoneAxesViewer;
  85230. }(Debug.AxesViewer));
  85231. Debug.BoneAxesViewer = BoneAxesViewer;
  85232. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85233. })(BABYLON || (BABYLON = {}));
  85234. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85235. var BABYLON;
  85236. (function (BABYLON) {
  85237. var RayHelper = /** @class */ (function () {
  85238. function RayHelper(ray) {
  85239. this.ray = ray;
  85240. }
  85241. RayHelper.CreateAndShow = function (ray, scene, color) {
  85242. var helper = new RayHelper(ray);
  85243. helper.show(scene, color);
  85244. return helper;
  85245. };
  85246. RayHelper.prototype.show = function (scene, color) {
  85247. if (!this._renderFunction && this.ray) {
  85248. var ray = this.ray;
  85249. this._renderFunction = this._render.bind(this);
  85250. this._scene = scene;
  85251. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85252. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85253. if (this._renderFunction) {
  85254. this._scene.registerBeforeRender(this._renderFunction);
  85255. }
  85256. }
  85257. if (color && this._renderLine) {
  85258. this._renderLine.color.copyFrom(color);
  85259. }
  85260. };
  85261. RayHelper.prototype.hide = function () {
  85262. if (this._renderFunction && this._scene) {
  85263. this._scene.unregisterBeforeRender(this._renderFunction);
  85264. this._scene = null;
  85265. this._renderFunction = null;
  85266. if (this._renderLine) {
  85267. this._renderLine.dispose();
  85268. this._renderLine = null;
  85269. }
  85270. this._renderPoints = [];
  85271. }
  85272. };
  85273. RayHelper.prototype._render = function () {
  85274. var ray = this.ray;
  85275. if (!ray) {
  85276. return;
  85277. }
  85278. var point = this._renderPoints[1];
  85279. var len = Math.min(ray.length, 1000000);
  85280. point.copyFrom(ray.direction);
  85281. point.scaleInPlace(len);
  85282. point.addInPlace(ray.origin);
  85283. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85284. };
  85285. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85286. this._attachedToMesh = mesh;
  85287. var ray = this.ray;
  85288. if (!ray) {
  85289. return;
  85290. }
  85291. if (!ray.direction) {
  85292. ray.direction = BABYLON.Vector3.Zero();
  85293. }
  85294. if (!ray.origin) {
  85295. ray.origin = BABYLON.Vector3.Zero();
  85296. }
  85297. if (length) {
  85298. ray.length = length;
  85299. }
  85300. if (!meshSpaceOrigin) {
  85301. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85302. }
  85303. if (!meshSpaceDirection) {
  85304. // -1 so that this will work with Mesh.lookAt
  85305. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85306. }
  85307. if (!this._meshSpaceDirection) {
  85308. this._meshSpaceDirection = meshSpaceDirection.clone();
  85309. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85310. }
  85311. else {
  85312. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85313. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85314. }
  85315. if (!this._updateToMeshFunction) {
  85316. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85317. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85318. }
  85319. this._updateToMesh();
  85320. };
  85321. RayHelper.prototype.detachFromMesh = function () {
  85322. if (this._attachedToMesh) {
  85323. if (this._updateToMeshFunction) {
  85324. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85325. }
  85326. this._attachedToMesh = null;
  85327. this._updateToMeshFunction = null;
  85328. }
  85329. };
  85330. RayHelper.prototype._updateToMesh = function () {
  85331. var ray = this.ray;
  85332. if (!this._attachedToMesh || !ray) {
  85333. return;
  85334. }
  85335. if (this._attachedToMesh._isDisposed) {
  85336. this.detachFromMesh();
  85337. return;
  85338. }
  85339. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85340. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85341. };
  85342. RayHelper.prototype.dispose = function () {
  85343. this.hide();
  85344. this.detachFromMesh();
  85345. this.ray = null;
  85346. };
  85347. return RayHelper;
  85348. }());
  85349. BABYLON.RayHelper = RayHelper;
  85350. })(BABYLON || (BABYLON = {}));
  85351. //# sourceMappingURL=babylon.rayHelper.js.map
  85352. var BABYLON;
  85353. (function (BABYLON) {
  85354. // load the inspector using require, if not present in the global namespace.
  85355. var DebugLayer = /** @class */ (function () {
  85356. function DebugLayer(scene) {
  85357. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85358. this._scene = scene;
  85359. // load inspector using require, if it doesn't exist on the global namespace.
  85360. }
  85361. /** Creates the inspector window. */
  85362. DebugLayer.prototype._createInspector = function (config) {
  85363. if (config === void 0) { config = {}; }
  85364. var popup = config.popup || false;
  85365. var initialTab = config.initialTab || 0;
  85366. var parentElement = config.parentElement || null;
  85367. if (!this._inspector) {
  85368. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85369. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85370. } // else nothing to do,; instance is already existing
  85371. };
  85372. DebugLayer.prototype.isVisible = function () {
  85373. if (!this._inspector) {
  85374. return false;
  85375. }
  85376. return true;
  85377. };
  85378. DebugLayer.prototype.hide = function () {
  85379. if (this._inspector) {
  85380. try {
  85381. this._inspector.dispose();
  85382. }
  85383. catch (e) {
  85384. // If the inspector has been removed directly from the inspector tool
  85385. }
  85386. this._inspector = null;
  85387. }
  85388. };
  85389. DebugLayer.prototype.show = function (config) {
  85390. if (config === void 0) { config = {}; }
  85391. if (typeof this.BJSINSPECTOR == 'undefined') {
  85392. // Load inspector and add it to the DOM
  85393. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85394. }
  85395. else {
  85396. // Otherwise creates the inspector
  85397. this._createInspector(config);
  85398. }
  85399. };
  85400. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85401. return DebugLayer;
  85402. }());
  85403. BABYLON.DebugLayer = DebugLayer;
  85404. })(BABYLON || (BABYLON = {}));
  85405. //# sourceMappingURL=babylon.debugLayer.js.map
  85406. var BABYLON;
  85407. (function (BABYLON) {
  85408. var Debug;
  85409. (function (Debug) {
  85410. /**
  85411. * Used to show the physics impostor around the specific mesh.
  85412. */
  85413. var PhysicsViewer = /** @class */ (function () {
  85414. function PhysicsViewer(scene) {
  85415. this._impostors = [];
  85416. this._meshes = [];
  85417. this._numMeshes = 0;
  85418. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85419. var physicEngine = this._scene.getPhysicsEngine();
  85420. if (physicEngine) {
  85421. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85422. }
  85423. }
  85424. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85425. var plugin = this._physicsEnginePlugin;
  85426. for (var i = 0; i < this._numMeshes; i++) {
  85427. var impostor = this._impostors[i];
  85428. if (!impostor) {
  85429. continue;
  85430. }
  85431. if (impostor.isDisposed) {
  85432. this.hideImpostor(this._impostors[i--]);
  85433. }
  85434. else {
  85435. var mesh = this._meshes[i];
  85436. if (mesh && plugin) {
  85437. plugin.syncMeshWithImpostor(mesh, impostor);
  85438. }
  85439. }
  85440. }
  85441. };
  85442. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85443. if (!this._scene) {
  85444. return;
  85445. }
  85446. for (var i = 0; i < this._numMeshes; i++) {
  85447. if (this._impostors[i] == impostor) {
  85448. return;
  85449. }
  85450. }
  85451. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85452. if (debugMesh) {
  85453. this._impostors[this._numMeshes] = impostor;
  85454. this._meshes[this._numMeshes] = debugMesh;
  85455. if (this._numMeshes === 0) {
  85456. this._renderFunction = this._updateDebugMeshes.bind(this);
  85457. this._scene.registerBeforeRender(this._renderFunction);
  85458. }
  85459. this._numMeshes++;
  85460. }
  85461. };
  85462. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85463. if (!impostor || !this._scene) {
  85464. return;
  85465. }
  85466. var removed = false;
  85467. for (var i = 0; i < this._numMeshes; i++) {
  85468. if (this._impostors[i] == impostor) {
  85469. var mesh = this._meshes[i];
  85470. if (!mesh) {
  85471. continue;
  85472. }
  85473. this._scene.removeMesh(mesh);
  85474. mesh.dispose();
  85475. this._numMeshes--;
  85476. if (this._numMeshes > 0) {
  85477. this._meshes[i] = this._meshes[this._numMeshes];
  85478. this._impostors[i] = this._impostors[this._numMeshes];
  85479. this._meshes[this._numMeshes] = null;
  85480. this._impostors[this._numMeshes] = null;
  85481. }
  85482. else {
  85483. this._meshes[0] = null;
  85484. this._impostors[0] = null;
  85485. }
  85486. removed = true;
  85487. break;
  85488. }
  85489. }
  85490. if (removed && this._numMeshes === 0) {
  85491. this._scene.unregisterBeforeRender(this._renderFunction);
  85492. }
  85493. };
  85494. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85495. if (!this._debugMaterial) {
  85496. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85497. this._debugMaterial.wireframe = true;
  85498. }
  85499. return this._debugMaterial;
  85500. };
  85501. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85502. if (!this._debugBoxMesh) {
  85503. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85504. this._debugBoxMesh.renderingGroupId = 1;
  85505. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85506. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85507. scene.removeMesh(this._debugBoxMesh);
  85508. }
  85509. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85510. };
  85511. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85512. if (!this._debugSphereMesh) {
  85513. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85514. this._debugSphereMesh.renderingGroupId = 1;
  85515. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85516. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85517. scene.removeMesh(this._debugSphereMesh);
  85518. }
  85519. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85520. };
  85521. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85522. var mesh = null;
  85523. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85524. mesh = this._getDebugBoxMesh(scene);
  85525. impostor.getBoxSizeToRef(mesh.scaling);
  85526. }
  85527. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85528. mesh = this._getDebugSphereMesh(scene);
  85529. var radius = impostor.getRadius();
  85530. mesh.scaling.x = radius * 2;
  85531. mesh.scaling.y = radius * 2;
  85532. mesh.scaling.z = radius * 2;
  85533. }
  85534. return mesh;
  85535. };
  85536. PhysicsViewer.prototype.dispose = function () {
  85537. for (var i = 0; i < this._numMeshes; i++) {
  85538. this.hideImpostor(this._impostors[i]);
  85539. }
  85540. if (this._debugBoxMesh) {
  85541. this._debugBoxMesh.dispose();
  85542. }
  85543. if (this._debugSphereMesh) {
  85544. this._debugSphereMesh.dispose();
  85545. }
  85546. if (this._debugMaterial) {
  85547. this._debugMaterial.dispose();
  85548. }
  85549. this._impostors.length = 0;
  85550. this._scene = null;
  85551. this._physicsEnginePlugin = null;
  85552. };
  85553. return PhysicsViewer;
  85554. }());
  85555. Debug.PhysicsViewer = PhysicsViewer;
  85556. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85557. })(BABYLON || (BABYLON = {}));
  85558. //# sourceMappingURL=babylon.physicsViewer.js.map
  85559. var BABYLON;
  85560. (function (BABYLON) {
  85561. var BoundingBoxRenderer = /** @class */ (function () {
  85562. function BoundingBoxRenderer(scene) {
  85563. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85564. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85565. this.showBackLines = true;
  85566. this.renderList = new BABYLON.SmartArray(32);
  85567. this._vertexBuffers = {};
  85568. this._scene = scene;
  85569. }
  85570. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85571. if (this._colorShader) {
  85572. return;
  85573. }
  85574. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85575. attributes: [BABYLON.VertexBuffer.PositionKind],
  85576. uniforms: ["world", "viewProjection", "color"]
  85577. });
  85578. var engine = this._scene.getEngine();
  85579. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85580. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85581. this._createIndexBuffer();
  85582. };
  85583. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85584. var engine = this._scene.getEngine();
  85585. 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]);
  85586. };
  85587. BoundingBoxRenderer.prototype._rebuild = function () {
  85588. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85589. if (vb) {
  85590. vb._rebuild();
  85591. }
  85592. this._createIndexBuffer();
  85593. };
  85594. BoundingBoxRenderer.prototype.reset = function () {
  85595. this.renderList.reset();
  85596. };
  85597. BoundingBoxRenderer.prototype.render = function () {
  85598. if (this.renderList.length === 0) {
  85599. return;
  85600. }
  85601. this._prepareRessources();
  85602. if (!this._colorShader.isReady()) {
  85603. return;
  85604. }
  85605. var engine = this._scene.getEngine();
  85606. engine.setDepthWrite(false);
  85607. this._colorShader._preBind();
  85608. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85609. var boundingBox = this.renderList.data[boundingBoxIndex];
  85610. var min = boundingBox.minimum;
  85611. var max = boundingBox.maximum;
  85612. var diff = max.subtract(min);
  85613. var median = min.add(diff.scale(0.5));
  85614. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85615. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85616. .multiply(boundingBox.getWorldMatrix());
  85617. // VBOs
  85618. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85619. if (this.showBackLines) {
  85620. // Back
  85621. engine.setDepthFunctionToGreaterOrEqual();
  85622. this._scene.resetCachedMaterial();
  85623. this._colorShader.setColor4("color", this.backColor.toColor4());
  85624. this._colorShader.bind(worldMatrix);
  85625. // Draw order
  85626. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85627. }
  85628. // Front
  85629. engine.setDepthFunctionToLess();
  85630. this._scene.resetCachedMaterial();
  85631. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85632. this._colorShader.bind(worldMatrix);
  85633. // Draw order
  85634. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85635. }
  85636. this._colorShader.unbind();
  85637. engine.setDepthFunctionToLessOrEqual();
  85638. engine.setDepthWrite(true);
  85639. };
  85640. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85641. this._prepareRessources();
  85642. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85643. return;
  85644. }
  85645. var engine = this._scene.getEngine();
  85646. engine.setDepthWrite(false);
  85647. engine.setColorWrite(false);
  85648. this._colorShader._preBind();
  85649. var boundingBox = mesh._boundingInfo.boundingBox;
  85650. var min = boundingBox.minimum;
  85651. var max = boundingBox.maximum;
  85652. var diff = max.subtract(min);
  85653. var median = min.add(diff.scale(0.5));
  85654. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85655. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85656. .multiply(boundingBox.getWorldMatrix());
  85657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85658. engine.setDepthFunctionToLess();
  85659. this._scene.resetCachedMaterial();
  85660. this._colorShader.bind(worldMatrix);
  85661. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85662. this._colorShader.unbind();
  85663. engine.setDepthFunctionToLessOrEqual();
  85664. engine.setDepthWrite(true);
  85665. engine.setColorWrite(true);
  85666. };
  85667. BoundingBoxRenderer.prototype.dispose = function () {
  85668. if (!this._colorShader) {
  85669. return;
  85670. }
  85671. this.renderList.dispose();
  85672. this._colorShader.dispose();
  85673. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85674. if (buffer) {
  85675. buffer.dispose();
  85676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85677. }
  85678. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85679. };
  85680. return BoundingBoxRenderer;
  85681. }());
  85682. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85683. })(BABYLON || (BABYLON = {}));
  85684. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85685. var BABYLON;
  85686. (function (BABYLON) {
  85687. /**
  85688. * Defines a target to use with MorphTargetManager
  85689. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85690. */
  85691. var MorphTarget = /** @class */ (function () {
  85692. /**
  85693. * Creates a new MorphTarget
  85694. * @param name defines the name of the target
  85695. * @param influence defines the influence to use
  85696. */
  85697. function MorphTarget(
  85698. /** defines the name of the target */
  85699. name, influence, scene) {
  85700. if (influence === void 0) { influence = 0; }
  85701. if (scene === void 0) { scene = null; }
  85702. this.name = name;
  85703. /**
  85704. * Gets or sets the list of animations
  85705. */
  85706. this.animations = new Array();
  85707. this._positions = null;
  85708. this._normals = null;
  85709. this._tangents = null;
  85710. /**
  85711. * Observable raised when the influence changes
  85712. */
  85713. this.onInfluenceChanged = new BABYLON.Observable();
  85714. this._animationPropertiesOverride = null;
  85715. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85716. this.influence = influence;
  85717. }
  85718. Object.defineProperty(MorphTarget.prototype, "influence", {
  85719. /**
  85720. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85721. */
  85722. get: function () {
  85723. return this._influence;
  85724. },
  85725. set: function (influence) {
  85726. if (this._influence === influence) {
  85727. return;
  85728. }
  85729. var previous = this._influence;
  85730. this._influence = influence;
  85731. if (this.onInfluenceChanged.hasObservers) {
  85732. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85733. }
  85734. },
  85735. enumerable: true,
  85736. configurable: true
  85737. });
  85738. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85739. /**
  85740. * Gets or sets the animation properties override
  85741. */
  85742. get: function () {
  85743. if (!this._animationPropertiesOverride && this._scene) {
  85744. return this._scene.animationPropertiesOverride;
  85745. }
  85746. return this._animationPropertiesOverride;
  85747. },
  85748. set: function (value) {
  85749. this._animationPropertiesOverride = value;
  85750. },
  85751. enumerable: true,
  85752. configurable: true
  85753. });
  85754. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85755. /**
  85756. * Gets a boolean defining if the target contains position data
  85757. */
  85758. get: function () {
  85759. return !!this._positions;
  85760. },
  85761. enumerable: true,
  85762. configurable: true
  85763. });
  85764. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85765. /**
  85766. * Gets a boolean defining if the target contains normal data
  85767. */
  85768. get: function () {
  85769. return !!this._normals;
  85770. },
  85771. enumerable: true,
  85772. configurable: true
  85773. });
  85774. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85775. /**
  85776. * Gets a boolean defining if the target contains tangent data
  85777. */
  85778. get: function () {
  85779. return !!this._tangents;
  85780. },
  85781. enumerable: true,
  85782. configurable: true
  85783. });
  85784. /**
  85785. * Affects position data to this target
  85786. * @param data defines the position data to use
  85787. */
  85788. MorphTarget.prototype.setPositions = function (data) {
  85789. this._positions = data;
  85790. };
  85791. /**
  85792. * Gets the position data stored in this target
  85793. * @returns a FloatArray containing the position data (or null if not present)
  85794. */
  85795. MorphTarget.prototype.getPositions = function () {
  85796. return this._positions;
  85797. };
  85798. /**
  85799. * Affects normal data to this target
  85800. * @param data defines the normal data to use
  85801. */
  85802. MorphTarget.prototype.setNormals = function (data) {
  85803. this._normals = data;
  85804. };
  85805. /**
  85806. * Gets the normal data stored in this target
  85807. * @returns a FloatArray containing the normal data (or null if not present)
  85808. */
  85809. MorphTarget.prototype.getNormals = function () {
  85810. return this._normals;
  85811. };
  85812. /**
  85813. * Affects tangent data to this target
  85814. * @param data defines the tangent data to use
  85815. */
  85816. MorphTarget.prototype.setTangents = function (data) {
  85817. this._tangents = data;
  85818. };
  85819. /**
  85820. * Gets the tangent data stored in this target
  85821. * @returns a FloatArray containing the tangent data (or null if not present)
  85822. */
  85823. MorphTarget.prototype.getTangents = function () {
  85824. return this._tangents;
  85825. };
  85826. /**
  85827. * Serializes the current target into a Serialization object
  85828. * @returns the serialized object
  85829. */
  85830. MorphTarget.prototype.serialize = function () {
  85831. var serializationObject = {};
  85832. serializationObject.name = this.name;
  85833. serializationObject.influence = this.influence;
  85834. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85835. if (this.hasNormals) {
  85836. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85837. }
  85838. if (this.hasTangents) {
  85839. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85840. }
  85841. // Animations
  85842. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85843. return serializationObject;
  85844. };
  85845. // Statics
  85846. /**
  85847. * Creates a new target from serialized data
  85848. * @param serializationObject defines the serialized data to use
  85849. * @returns a new MorphTarget
  85850. */
  85851. MorphTarget.Parse = function (serializationObject) {
  85852. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85853. result.setPositions(serializationObject.positions);
  85854. if (serializationObject.normals) {
  85855. result.setNormals(serializationObject.normals);
  85856. }
  85857. if (serializationObject.tangents) {
  85858. result.setTangents(serializationObject.tangents);
  85859. }
  85860. // Animations
  85861. if (serializationObject.animations) {
  85862. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85863. var parsedAnimation = serializationObject.animations[animationIndex];
  85864. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85865. }
  85866. }
  85867. return result;
  85868. };
  85869. /**
  85870. * Creates a MorphTarget from mesh data
  85871. * @param mesh defines the source mesh
  85872. * @param name defines the name to use for the new target
  85873. * @param influence defines the influence to attach to the target
  85874. * @returns a new MorphTarget
  85875. */
  85876. MorphTarget.FromMesh = function (mesh, name, influence) {
  85877. if (!name) {
  85878. name = mesh.name;
  85879. }
  85880. var result = new MorphTarget(name, influence, mesh.getScene());
  85881. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85882. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85883. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85884. }
  85885. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85886. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85887. }
  85888. return result;
  85889. };
  85890. return MorphTarget;
  85891. }());
  85892. BABYLON.MorphTarget = MorphTarget;
  85893. })(BABYLON || (BABYLON = {}));
  85894. //# sourceMappingURL=babylon.morphTarget.js.map
  85895. var BABYLON;
  85896. (function (BABYLON) {
  85897. /**
  85898. * This class is used to deform meshes using morphing between different targets
  85899. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85900. */
  85901. var MorphTargetManager = /** @class */ (function () {
  85902. /**
  85903. * Creates a new MorphTargetManager
  85904. * @param scene defines the current scene
  85905. */
  85906. function MorphTargetManager(scene) {
  85907. if (scene === void 0) { scene = null; }
  85908. this._targets = new Array();
  85909. this._targetObservable = new Array();
  85910. this._activeTargets = new BABYLON.SmartArray(16);
  85911. this._supportsNormals = false;
  85912. this._supportsTangents = false;
  85913. this._vertexCount = 0;
  85914. this._uniqueId = 0;
  85915. this._tempInfluences = new Array();
  85916. if (!scene) {
  85917. scene = BABYLON.Engine.LastCreatedScene;
  85918. }
  85919. this._scene = scene;
  85920. if (this._scene) {
  85921. this._scene.morphTargetManagers.push(this);
  85922. this._uniqueId = this._scene.getUniqueId();
  85923. }
  85924. }
  85925. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85926. /**
  85927. * Gets the unique ID of this manager
  85928. */
  85929. get: function () {
  85930. return this._uniqueId;
  85931. },
  85932. enumerable: true,
  85933. configurable: true
  85934. });
  85935. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85936. /**
  85937. * Gets the number of vertices handled by this manager
  85938. */
  85939. get: function () {
  85940. return this._vertexCount;
  85941. },
  85942. enumerable: true,
  85943. configurable: true
  85944. });
  85945. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85946. /**
  85947. * Gets a boolean indicating if this manager supports morphing of normals
  85948. */
  85949. get: function () {
  85950. return this._supportsNormals;
  85951. },
  85952. enumerable: true,
  85953. configurable: true
  85954. });
  85955. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85956. /**
  85957. * Gets a boolean indicating if this manager supports morphing of tangents
  85958. */
  85959. get: function () {
  85960. return this._supportsTangents;
  85961. },
  85962. enumerable: true,
  85963. configurable: true
  85964. });
  85965. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85966. /**
  85967. * Gets the number of targets stored in this manager
  85968. */
  85969. get: function () {
  85970. return this._targets.length;
  85971. },
  85972. enumerable: true,
  85973. configurable: true
  85974. });
  85975. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85976. /**
  85977. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85978. */
  85979. get: function () {
  85980. return this._activeTargets.length;
  85981. },
  85982. enumerable: true,
  85983. configurable: true
  85984. });
  85985. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85986. /**
  85987. * Gets the list of influences (one per target)
  85988. */
  85989. get: function () {
  85990. return this._influences;
  85991. },
  85992. enumerable: true,
  85993. configurable: true
  85994. });
  85995. /**
  85996. * Gets the active target at specified index. An active target is a target with an influence > 0
  85997. * @param index defines the index to check
  85998. * @returns the requested target
  85999. */
  86000. MorphTargetManager.prototype.getActiveTarget = function (index) {
  86001. return this._activeTargets.data[index];
  86002. };
  86003. /**
  86004. * Gets the target at specified index
  86005. * @param index defines the index to check
  86006. * @returns the requested target
  86007. */
  86008. MorphTargetManager.prototype.getTarget = function (index) {
  86009. return this._targets[index];
  86010. };
  86011. /**
  86012. * Add a new target to this manager
  86013. * @param target defines the target to add
  86014. */
  86015. MorphTargetManager.prototype.addTarget = function (target) {
  86016. var _this = this;
  86017. this._targets.push(target);
  86018. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  86019. _this._syncActiveTargets(needUpdate);
  86020. }));
  86021. this._syncActiveTargets(true);
  86022. };
  86023. /**
  86024. * Removes a target from the manager
  86025. * @param target defines the target to remove
  86026. */
  86027. MorphTargetManager.prototype.removeTarget = function (target) {
  86028. var index = this._targets.indexOf(target);
  86029. if (index >= 0) {
  86030. this._targets.splice(index, 1);
  86031. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86032. this._syncActiveTargets(true);
  86033. }
  86034. };
  86035. /**
  86036. * Serializes the current manager into a Serialization object
  86037. * @returns the serialized object
  86038. */
  86039. MorphTargetManager.prototype.serialize = function () {
  86040. var serializationObject = {};
  86041. serializationObject.id = this.uniqueId;
  86042. serializationObject.targets = [];
  86043. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86044. var target = _a[_i];
  86045. serializationObject.targets.push(target.serialize());
  86046. }
  86047. return serializationObject;
  86048. };
  86049. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86050. var influenceCount = 0;
  86051. this._activeTargets.reset();
  86052. this._supportsNormals = true;
  86053. this._supportsTangents = true;
  86054. this._vertexCount = 0;
  86055. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86056. var target = _a[_i];
  86057. this._activeTargets.push(target);
  86058. this._tempInfluences[influenceCount++] = target.influence;
  86059. var positions = target.getPositions();
  86060. if (positions) {
  86061. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86062. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86063. var vertexCount = positions.length / 3;
  86064. if (this._vertexCount === 0) {
  86065. this._vertexCount = vertexCount;
  86066. }
  86067. else if (this._vertexCount !== vertexCount) {
  86068. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86069. return;
  86070. }
  86071. }
  86072. }
  86073. if (!this._influences || this._influences.length !== influenceCount) {
  86074. this._influences = new Float32Array(influenceCount);
  86075. }
  86076. for (var index = 0; index < influenceCount; index++) {
  86077. this._influences[index] = this._tempInfluences[index];
  86078. }
  86079. if (needUpdate) {
  86080. this.synchronize();
  86081. }
  86082. };
  86083. /**
  86084. * Syncrhonize the targets with all the meshes using this morph target manager
  86085. */
  86086. MorphTargetManager.prototype.synchronize = function () {
  86087. if (!this._scene) {
  86088. return;
  86089. }
  86090. // Flag meshes as dirty to resync with the active targets
  86091. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86092. var mesh = _a[_i];
  86093. if (mesh.morphTargetManager === this) {
  86094. mesh._syncGeometryWithMorphTargetManager();
  86095. }
  86096. }
  86097. };
  86098. // Statics
  86099. /**
  86100. * Creates a new MorphTargetManager from serialized data
  86101. * @param serializationObject defines the serialized data
  86102. * @param scene defines the hosting scene
  86103. * @returns the new MorphTargetManager
  86104. */
  86105. MorphTargetManager.Parse = function (serializationObject, scene) {
  86106. var result = new MorphTargetManager(scene);
  86107. result._uniqueId = serializationObject.id;
  86108. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86109. var targetData = _a[_i];
  86110. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86111. }
  86112. return result;
  86113. };
  86114. return MorphTargetManager;
  86115. }());
  86116. BABYLON.MorphTargetManager = MorphTargetManager;
  86117. })(BABYLON || (BABYLON = {}));
  86118. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86119. var BABYLON;
  86120. (function (BABYLON) {
  86121. var Octree = /** @class */ (function () {
  86122. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86123. if (maxDepth === void 0) { maxDepth = 2; }
  86124. this.maxDepth = maxDepth;
  86125. this.dynamicContent = new Array();
  86126. this._maxBlockCapacity = maxBlockCapacity || 64;
  86127. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86128. this._creationFunc = creationFunc;
  86129. }
  86130. // Methods
  86131. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86132. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86133. };
  86134. Octree.prototype.addMesh = function (entry) {
  86135. for (var index = 0; index < this.blocks.length; index++) {
  86136. var block = this.blocks[index];
  86137. block.addEntry(entry);
  86138. }
  86139. };
  86140. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86141. this._selectionContent.reset();
  86142. for (var index = 0; index < this.blocks.length; index++) {
  86143. var block = this.blocks[index];
  86144. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86145. }
  86146. if (allowDuplicate) {
  86147. this._selectionContent.concat(this.dynamicContent);
  86148. }
  86149. else {
  86150. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86151. }
  86152. return this._selectionContent;
  86153. };
  86154. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86155. this._selectionContent.reset();
  86156. for (var index = 0; index < this.blocks.length; index++) {
  86157. var block = this.blocks[index];
  86158. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86159. }
  86160. if (allowDuplicate) {
  86161. this._selectionContent.concat(this.dynamicContent);
  86162. }
  86163. else {
  86164. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86165. }
  86166. return this._selectionContent;
  86167. };
  86168. Octree.prototype.intersectsRay = function (ray) {
  86169. this._selectionContent.reset();
  86170. for (var index = 0; index < this.blocks.length; index++) {
  86171. var block = this.blocks[index];
  86172. block.intersectsRay(ray, this._selectionContent);
  86173. }
  86174. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86175. return this._selectionContent;
  86176. };
  86177. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86178. target.blocks = new Array();
  86179. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86180. // Segmenting space
  86181. for (var x = 0; x < 2; x++) {
  86182. for (var y = 0; y < 2; y++) {
  86183. for (var z = 0; z < 2; z++) {
  86184. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86185. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86186. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86187. block.addEntries(entries);
  86188. target.blocks.push(block);
  86189. }
  86190. }
  86191. }
  86192. };
  86193. Octree.CreationFuncForMeshes = function (entry, block) {
  86194. var boundingInfo = entry.getBoundingInfo();
  86195. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86196. block.entries.push(entry);
  86197. }
  86198. };
  86199. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86200. var boundingInfo = entry.getBoundingInfo();
  86201. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86202. block.entries.push(entry);
  86203. }
  86204. };
  86205. return Octree;
  86206. }());
  86207. BABYLON.Octree = Octree;
  86208. })(BABYLON || (BABYLON = {}));
  86209. //# sourceMappingURL=babylon.octree.js.map
  86210. var BABYLON;
  86211. (function (BABYLON) {
  86212. var OctreeBlock = /** @class */ (function () {
  86213. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86214. this.entries = new Array();
  86215. this._boundingVectors = new Array();
  86216. this._capacity = capacity;
  86217. this._depth = depth;
  86218. this._maxDepth = maxDepth;
  86219. this._creationFunc = creationFunc;
  86220. this._minPoint = minPoint;
  86221. this._maxPoint = maxPoint;
  86222. this._boundingVectors.push(minPoint.clone());
  86223. this._boundingVectors.push(maxPoint.clone());
  86224. this._boundingVectors.push(minPoint.clone());
  86225. this._boundingVectors[2].x = maxPoint.x;
  86226. this._boundingVectors.push(minPoint.clone());
  86227. this._boundingVectors[3].y = maxPoint.y;
  86228. this._boundingVectors.push(minPoint.clone());
  86229. this._boundingVectors[4].z = maxPoint.z;
  86230. this._boundingVectors.push(maxPoint.clone());
  86231. this._boundingVectors[5].z = minPoint.z;
  86232. this._boundingVectors.push(maxPoint.clone());
  86233. this._boundingVectors[6].x = minPoint.x;
  86234. this._boundingVectors.push(maxPoint.clone());
  86235. this._boundingVectors[7].y = minPoint.y;
  86236. }
  86237. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86238. // Property
  86239. get: function () {
  86240. return this._capacity;
  86241. },
  86242. enumerable: true,
  86243. configurable: true
  86244. });
  86245. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86246. get: function () {
  86247. return this._minPoint;
  86248. },
  86249. enumerable: true,
  86250. configurable: true
  86251. });
  86252. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86253. get: function () {
  86254. return this._maxPoint;
  86255. },
  86256. enumerable: true,
  86257. configurable: true
  86258. });
  86259. // Methods
  86260. OctreeBlock.prototype.addEntry = function (entry) {
  86261. if (this.blocks) {
  86262. for (var index = 0; index < this.blocks.length; index++) {
  86263. var block = this.blocks[index];
  86264. block.addEntry(entry);
  86265. }
  86266. return;
  86267. }
  86268. this._creationFunc(entry, this);
  86269. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86270. this.createInnerBlocks();
  86271. }
  86272. };
  86273. OctreeBlock.prototype.addEntries = function (entries) {
  86274. for (var index = 0; index < entries.length; index++) {
  86275. var mesh = entries[index];
  86276. this.addEntry(mesh);
  86277. }
  86278. };
  86279. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86280. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86281. if (this.blocks) {
  86282. for (var index = 0; index < this.blocks.length; index++) {
  86283. var block = this.blocks[index];
  86284. block.select(frustumPlanes, selection, allowDuplicate);
  86285. }
  86286. return;
  86287. }
  86288. if (allowDuplicate) {
  86289. selection.concat(this.entries);
  86290. }
  86291. else {
  86292. selection.concatWithNoDuplicate(this.entries);
  86293. }
  86294. }
  86295. };
  86296. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86297. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86298. if (this.blocks) {
  86299. for (var index = 0; index < this.blocks.length; index++) {
  86300. var block = this.blocks[index];
  86301. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86302. }
  86303. return;
  86304. }
  86305. if (allowDuplicate) {
  86306. selection.concat(this.entries);
  86307. }
  86308. else {
  86309. selection.concatWithNoDuplicate(this.entries);
  86310. }
  86311. }
  86312. };
  86313. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86314. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86315. if (this.blocks) {
  86316. for (var index = 0; index < this.blocks.length; index++) {
  86317. var block = this.blocks[index];
  86318. block.intersectsRay(ray, selection);
  86319. }
  86320. return;
  86321. }
  86322. selection.concatWithNoDuplicate(this.entries);
  86323. }
  86324. };
  86325. OctreeBlock.prototype.createInnerBlocks = function () {
  86326. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86327. };
  86328. return OctreeBlock;
  86329. }());
  86330. BABYLON.OctreeBlock = OctreeBlock;
  86331. })(BABYLON || (BABYLON = {}));
  86332. //# sourceMappingURL=babylon.octreeBlock.js.map
  86333. var BABYLON;
  86334. (function (BABYLON) {
  86335. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86336. __extends(VRDistortionCorrectionPostProcess, _super);
  86337. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86338. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86339. 'LensCenter',
  86340. 'Scale',
  86341. 'ScaleIn',
  86342. 'HmdWarpParam'
  86343. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86344. _this._isRightEye = isRightEye;
  86345. _this._distortionFactors = vrMetrics.distortionK;
  86346. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86347. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86348. _this.adaptScaleToCurrentViewport = true;
  86349. _this.onSizeChangedObservable.add(function () {
  86350. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86351. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86352. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86353. });
  86354. _this.onApplyObservable.add(function (effect) {
  86355. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86356. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86357. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86358. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86359. });
  86360. return _this;
  86361. }
  86362. return VRDistortionCorrectionPostProcess;
  86363. }(BABYLON.PostProcess));
  86364. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86365. })(BABYLON || (BABYLON = {}));
  86366. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86367. var BABYLON;
  86368. (function (BABYLON) {
  86369. /**
  86370. * Postprocess used to generate anaglyphic rendering
  86371. */
  86372. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86373. __extends(AnaglyphPostProcess, _super);
  86374. /**
  86375. * Creates a new AnaglyphPostProcess
  86376. * @param name defines postprocess name
  86377. * @param options defines creation options or target ratio scale
  86378. * @param rigCameras defines cameras using this postprocess
  86379. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86380. * @param engine defines hosting engine
  86381. * @param reusable defines if the postprocess will be reused multiple times per frame
  86382. */
  86383. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86384. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86385. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86386. _this.onApplyObservable.add(function (effect) {
  86387. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86388. });
  86389. return _this;
  86390. }
  86391. return AnaglyphPostProcess;
  86392. }(BABYLON.PostProcess));
  86393. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86394. })(BABYLON || (BABYLON = {}));
  86395. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86396. var BABYLON;
  86397. (function (BABYLON) {
  86398. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86399. __extends(StereoscopicInterlacePostProcess, _super);
  86400. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86401. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86402. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86403. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86404. _this.onSizeChangedObservable.add(function () {
  86405. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86406. });
  86407. _this.onApplyObservable.add(function (effect) {
  86408. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86409. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86410. });
  86411. return _this;
  86412. }
  86413. return StereoscopicInterlacePostProcess;
  86414. }(BABYLON.PostProcess));
  86415. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86416. })(BABYLON || (BABYLON = {}));
  86417. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86418. var BABYLON;
  86419. (function (BABYLON) {
  86420. /**
  86421. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86422. * Screen rotation is taken into account.
  86423. */
  86424. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86425. function FreeCameraDeviceOrientationInput() {
  86426. var _this = this;
  86427. this._screenOrientationAngle = 0;
  86428. this._screenQuaternion = new BABYLON.Quaternion();
  86429. this._alpha = 0;
  86430. this._beta = 0;
  86431. this._gamma = 0;
  86432. this._orientationChanged = function () {
  86433. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86434. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86435. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86436. };
  86437. this._deviceOrientation = function (evt) {
  86438. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86439. _this._beta = evt.beta !== null ? evt.beta : 0;
  86440. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86441. };
  86442. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86443. this._orientationChanged();
  86444. }
  86445. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86446. get: function () {
  86447. return this._camera;
  86448. },
  86449. set: function (camera) {
  86450. this._camera = camera;
  86451. if (this._camera != null && !this._camera.rotationQuaternion) {
  86452. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86453. }
  86454. },
  86455. enumerable: true,
  86456. configurable: true
  86457. });
  86458. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86459. window.addEventListener("orientationchange", this._orientationChanged);
  86460. window.addEventListener("deviceorientation", this._deviceOrientation);
  86461. //In certain cases, the attach control is called AFTER orientation was changed,
  86462. //So this is needed.
  86463. this._orientationChanged();
  86464. };
  86465. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86466. window.removeEventListener("orientationchange", this._orientationChanged);
  86467. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86468. };
  86469. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86470. //if no device orientation provided, don't update the rotation.
  86471. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86472. if (!this._alpha)
  86473. return;
  86474. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86475. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86476. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86477. //Mirror on XY Plane
  86478. this._camera.rotationQuaternion.z *= -1;
  86479. this._camera.rotationQuaternion.w *= -1;
  86480. };
  86481. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86482. return "FreeCameraDeviceOrientationInput";
  86483. };
  86484. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86485. return "deviceOrientation";
  86486. };
  86487. return FreeCameraDeviceOrientationInput;
  86488. }());
  86489. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86490. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86491. })(BABYLON || (BABYLON = {}));
  86492. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86493. var BABYLON;
  86494. (function (BABYLON) {
  86495. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86496. function ArcRotateCameraVRDeviceOrientationInput() {
  86497. this.alphaCorrection = 1;
  86498. this.betaCorrection = 1;
  86499. this.gammaCorrection = 1;
  86500. this._alpha = 0;
  86501. this._gamma = 0;
  86502. this._dirty = false;
  86503. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86504. }
  86505. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86506. this.camera.attachControl(element, noPreventDefault);
  86507. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86508. };
  86509. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86510. if (evt.alpha !== null) {
  86511. this._alpha = +evt.alpha | 0;
  86512. }
  86513. if (evt.gamma !== null) {
  86514. this._gamma = +evt.gamma | 0;
  86515. }
  86516. this._dirty = true;
  86517. };
  86518. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86519. if (this._dirty) {
  86520. this._dirty = false;
  86521. if (this._gamma < 0) {
  86522. this._gamma = 180 + this._gamma;
  86523. }
  86524. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86525. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86526. }
  86527. };
  86528. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86529. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86530. };
  86531. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86532. return "ArcRotateCameraVRDeviceOrientationInput";
  86533. };
  86534. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86535. return "VRDeviceOrientation";
  86536. };
  86537. return ArcRotateCameraVRDeviceOrientationInput;
  86538. }());
  86539. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86540. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86541. })(BABYLON || (BABYLON = {}));
  86542. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86543. var BABYLON;
  86544. (function (BABYLON) {
  86545. var VRCameraMetrics = /** @class */ (function () {
  86546. function VRCameraMetrics() {
  86547. this.compensateDistortion = true;
  86548. }
  86549. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86550. get: function () {
  86551. return this.hResolution / (2 * this.vResolution);
  86552. },
  86553. enumerable: true,
  86554. configurable: true
  86555. });
  86556. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86557. get: function () {
  86558. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86559. },
  86560. enumerable: true,
  86561. configurable: true
  86562. });
  86563. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86564. get: function () {
  86565. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86566. var h = (4 * meters) / this.hScreenSize;
  86567. return BABYLON.Matrix.Translation(h, 0, 0);
  86568. },
  86569. enumerable: true,
  86570. configurable: true
  86571. });
  86572. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86573. get: function () {
  86574. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86575. var h = (4 * meters) / this.hScreenSize;
  86576. return BABYLON.Matrix.Translation(-h, 0, 0);
  86577. },
  86578. enumerable: true,
  86579. configurable: true
  86580. });
  86581. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86582. get: function () {
  86583. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86584. },
  86585. enumerable: true,
  86586. configurable: true
  86587. });
  86588. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86589. get: function () {
  86590. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86591. },
  86592. enumerable: true,
  86593. configurable: true
  86594. });
  86595. VRCameraMetrics.GetDefault = function () {
  86596. var result = new VRCameraMetrics();
  86597. result.hResolution = 1280;
  86598. result.vResolution = 800;
  86599. result.hScreenSize = 0.149759993;
  86600. result.vScreenSize = 0.0935999975;
  86601. result.vScreenCenter = 0.0467999987;
  86602. result.eyeToScreenDistance = 0.0410000011;
  86603. result.lensSeparationDistance = 0.0635000020;
  86604. result.interpupillaryDistance = 0.0640000030;
  86605. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86606. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86607. result.postProcessScaleFactor = 1.714605507808412;
  86608. result.lensCenterOffset = 0.151976421;
  86609. return result;
  86610. };
  86611. return VRCameraMetrics;
  86612. }());
  86613. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86614. })(BABYLON || (BABYLON = {}));
  86615. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86616. var BABYLON;
  86617. (function (BABYLON) {
  86618. /**
  86619. * This represents a WebVR camera.
  86620. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86621. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86622. */
  86623. var WebVRFreeCamera = /** @class */ (function (_super) {
  86624. __extends(WebVRFreeCamera, _super);
  86625. /**
  86626. * Instantiates a WebVRFreeCamera.
  86627. * @param name The name of the WebVRFreeCamera
  86628. * @param position The starting anchor position for the camera
  86629. * @param scene The scene the camera belongs to
  86630. * @param webVROptions a set of customizable options for the webVRCamera
  86631. */
  86632. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86633. if (webVROptions === void 0) { webVROptions = {}; }
  86634. var _this = _super.call(this, name, position, scene) || this;
  86635. _this.webVROptions = webVROptions;
  86636. /**
  86637. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86638. */
  86639. _this._vrDevice = null;
  86640. /**
  86641. * The rawPose of the vrDevice.
  86642. */
  86643. _this.rawPose = null;
  86644. _this._specsVersion = "1.1";
  86645. _this._attached = false;
  86646. _this._descendants = [];
  86647. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86648. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86649. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86650. _this._standingMatrix = null;
  86651. /**
  86652. * Represents device position in babylon space.
  86653. */
  86654. _this.devicePosition = BABYLON.Vector3.Zero();
  86655. /**
  86656. * Represents device rotation in babylon space.
  86657. */
  86658. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86659. /**
  86660. * The scale of the device to be used when translating from device space to babylon space.
  86661. */
  86662. _this.deviceScaleFactor = 1;
  86663. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86664. _this._worldToDevice = BABYLON.Matrix.Identity();
  86665. /**
  86666. * References to the webVR controllers for the vrDevice.
  86667. */
  86668. _this.controllers = [];
  86669. /**
  86670. * Emits an event when a controller is attached.
  86671. */
  86672. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86673. /**
  86674. * Emits an event when a controller's mesh has been loaded;
  86675. */
  86676. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86677. /**
  86678. * If the rig cameras be used as parent instead of this camera.
  86679. */
  86680. _this.rigParenting = true;
  86681. _this._defaultHeight = undefined;
  86682. _this._workingVector = BABYLON.Vector3.Zero();
  86683. _this._oneVector = BABYLON.Vector3.One();
  86684. _this._workingMatrix = BABYLON.Matrix.Identity();
  86685. _this._cache.position = BABYLON.Vector3.Zero();
  86686. if (webVROptions.defaultHeight) {
  86687. _this._defaultHeight = webVROptions.defaultHeight;
  86688. _this.position.y = _this._defaultHeight;
  86689. }
  86690. _this.minZ = 0.1;
  86691. //legacy support - the compensation boolean was removed.
  86692. if (arguments.length === 5) {
  86693. _this.webVROptions = arguments[4];
  86694. }
  86695. // default webVR options
  86696. if (_this.webVROptions.trackPosition == undefined) {
  86697. _this.webVROptions.trackPosition = true;
  86698. }
  86699. if (_this.webVROptions.controllerMeshes == undefined) {
  86700. _this.webVROptions.controllerMeshes = true;
  86701. }
  86702. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86703. _this.webVROptions.defaultLightingOnControllers = true;
  86704. }
  86705. _this.rotationQuaternion = new BABYLON.Quaternion();
  86706. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86707. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86708. }
  86709. //enable VR
  86710. var engine = _this.getEngine();
  86711. _this._onVREnabled = function (success) { if (success) {
  86712. _this.initControllers();
  86713. } };
  86714. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86715. engine.initWebVR().add(function (event) {
  86716. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86717. return;
  86718. }
  86719. _this._vrDevice = event.vrDisplay;
  86720. //reset the rig parameters.
  86721. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86722. if (_this._attached) {
  86723. _this.getEngine().enableVR();
  86724. }
  86725. });
  86726. if (typeof (VRFrameData) !== "undefined")
  86727. _this._frameData = new VRFrameData();
  86728. /**
  86729. * The idea behind the following lines:
  86730. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86731. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86732. * the second will not show it correctly.
  86733. *
  86734. * To solve this - each object that has the camera as parent will be added to a protected array.
  86735. * When the rig camera renders, it will take this array and set all of those to be its children.
  86736. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86737. * Amazing!
  86738. */
  86739. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86740. if (camera.parent === _this && _this.rigParenting) {
  86741. _this._descendants = _this.getDescendants(true, function (n) {
  86742. // don't take the cameras or the controllers!
  86743. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86744. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86745. return !isController && !isRigCamera;
  86746. });
  86747. _this._descendants.forEach(function (node) {
  86748. node.parent = camera;
  86749. });
  86750. }
  86751. });
  86752. scene.onAfterCameraRenderObservable.add(function (camera) {
  86753. if (camera.parent === _this && _this.rigParenting) {
  86754. _this._descendants.forEach(function (node) {
  86755. node.parent = _this;
  86756. });
  86757. }
  86758. });
  86759. return _this;
  86760. }
  86761. /**
  86762. * Gets the device distance from the ground in meters.
  86763. * @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.
  86764. */
  86765. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86766. if (this._standingMatrix) {
  86767. // Add standing matrix offset to get real offset from ground in room
  86768. this._standingMatrix.getTranslationToRef(this._workingVector);
  86769. return this._deviceRoomPosition.y + this._workingVector.y;
  86770. }
  86771. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86772. return this._defaultHeight || 0;
  86773. };
  86774. /**
  86775. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86776. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86777. */
  86778. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86779. var _this = this;
  86780. if (callback === void 0) { callback = function (bool) { }; }
  86781. // Use standing matrix if available
  86782. this.getEngine().initWebVRAsync().then(function (result) {
  86783. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86784. callback(false);
  86785. }
  86786. else {
  86787. _this._standingMatrix = new BABYLON.Matrix();
  86788. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86789. if (!_this.getScene().useRightHandedSystem) {
  86790. [2, 6, 8, 9, 14].forEach(function (num) {
  86791. if (_this._standingMatrix) {
  86792. _this._standingMatrix.m[num] *= -1;
  86793. }
  86794. });
  86795. }
  86796. callback(true);
  86797. }
  86798. });
  86799. };
  86800. /**
  86801. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86802. * @returns A promise with a boolean set to if the standing matrix is supported.
  86803. */
  86804. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86805. var _this = this;
  86806. return new Promise(function (res, rej) {
  86807. _this.useStandingMatrix(function (supported) {
  86808. res(supported);
  86809. });
  86810. });
  86811. };
  86812. /**
  86813. * Disposes the camera
  86814. */
  86815. WebVRFreeCamera.prototype.dispose = function () {
  86816. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86817. _super.prototype.dispose.call(this);
  86818. };
  86819. /**
  86820. * Gets a vrController by name.
  86821. * @param name The name of the controller to retreive
  86822. * @returns the controller matching the name specified or null if not found
  86823. */
  86824. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86825. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86826. var gp = _a[_i];
  86827. if (gp.hand === name) {
  86828. return gp;
  86829. }
  86830. }
  86831. return null;
  86832. };
  86833. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86834. /**
  86835. * The controller corrisponding to the users left hand.
  86836. */
  86837. get: function () {
  86838. if (!this._leftController) {
  86839. this._leftController = this.getControllerByName("left");
  86840. }
  86841. return this._leftController;
  86842. },
  86843. enumerable: true,
  86844. configurable: true
  86845. });
  86846. ;
  86847. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86848. /**
  86849. * The controller corrisponding to the users right hand.
  86850. */
  86851. get: function () {
  86852. if (!this._rightController) {
  86853. this._rightController = this.getControllerByName("right");
  86854. }
  86855. return this._rightController;
  86856. },
  86857. enumerable: true,
  86858. configurable: true
  86859. });
  86860. ;
  86861. /**
  86862. * Casts a ray forward from the vrCamera's gaze.
  86863. * @param length Length of the ray (default: 100)
  86864. * @returns the ray corrisponding to the gaze
  86865. */
  86866. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86867. if (length === void 0) { length = 100; }
  86868. if (this.leftCamera) {
  86869. // Use left eye to avoid computation to compute center on every call
  86870. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86871. }
  86872. else {
  86873. return _super.prototype.getForwardRay.call(this, length);
  86874. }
  86875. };
  86876. /**
  86877. * Updates the camera based on device's frame data
  86878. */
  86879. WebVRFreeCamera.prototype._checkInputs = function () {
  86880. if (this._vrDevice && this._vrDevice.isPresenting) {
  86881. this._vrDevice.getFrameData(this._frameData);
  86882. this.updateFromDevice(this._frameData.pose);
  86883. }
  86884. _super.prototype._checkInputs.call(this);
  86885. };
  86886. /**
  86887. * Updates the poseControlled values based on the input device pose.
  86888. * @param poseData Pose coming from the device
  86889. */
  86890. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86891. if (poseData && poseData.orientation) {
  86892. this.rawPose = poseData;
  86893. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86894. if (this.getScene().useRightHandedSystem) {
  86895. this._deviceRoomRotationQuaternion.z *= -1;
  86896. this._deviceRoomRotationQuaternion.w *= -1;
  86897. }
  86898. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86899. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86900. if (this.getScene().useRightHandedSystem) {
  86901. this._deviceRoomPosition.z *= -1;
  86902. }
  86903. }
  86904. }
  86905. };
  86906. /**
  86907. * WebVR's attach control will start broadcasting frames to the device.
  86908. * Note that in certain browsers (chrome for example) this function must be called
  86909. * within a user-interaction callback. Example:
  86910. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86911. *
  86912. * @param element html element to attach the vrDevice to
  86913. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86914. */
  86915. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86916. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86917. this._attached = true;
  86918. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86919. if (this._vrDevice) {
  86920. this.getEngine().enableVR();
  86921. }
  86922. };
  86923. /**
  86924. * Detaches the camera from the html element and disables VR
  86925. *
  86926. * @param element html element to detach from
  86927. */
  86928. WebVRFreeCamera.prototype.detachControl = function (element) {
  86929. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86930. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86931. _super.prototype.detachControl.call(this, element);
  86932. this._attached = false;
  86933. this.getEngine().disableVR();
  86934. };
  86935. /**
  86936. * @returns the name of this class
  86937. */
  86938. WebVRFreeCamera.prototype.getClassName = function () {
  86939. return "WebVRFreeCamera";
  86940. };
  86941. /**
  86942. * Calls resetPose on the vrDisplay
  86943. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86944. */
  86945. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86946. //uses the vrDisplay's "resetPose()".
  86947. //pitch and roll won't be affected.
  86948. this._vrDevice.resetPose();
  86949. };
  86950. /**
  86951. * Updates the rig cameras (left and right eye)
  86952. */
  86953. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86954. var camLeft = this._rigCameras[0];
  86955. var camRight = this._rigCameras[1];
  86956. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86957. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86958. camLeft.position.copyFrom(this._deviceRoomPosition);
  86959. camRight.position.copyFrom(this._deviceRoomPosition);
  86960. };
  86961. /**
  86962. * Updates the cached values of the camera
  86963. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86964. */
  86965. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86966. var _this = this;
  86967. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86968. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86969. if (!this.updateCacheCalled) {
  86970. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86971. this.updateCacheCalled = true;
  86972. this.update();
  86973. }
  86974. // Set working vector to the device position in room space rotated by the new rotation
  86975. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86976. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86977. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86978. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86979. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86980. // Add translation from anchor position
  86981. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86982. this._workingVector.addInPlace(this.position);
  86983. this._workingVector.subtractInPlace(this._cache.position);
  86984. this._deviceToWorld.setTranslation(this._workingVector);
  86985. // Set an inverted matrix to be used when updating the camera
  86986. this._deviceToWorld.invertToRef(this._worldToDevice);
  86987. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86988. this.controllers.forEach(function (controller) {
  86989. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86990. controller.update();
  86991. });
  86992. }
  86993. if (!ignoreParentClass) {
  86994. _super.prototype._updateCache.call(this);
  86995. }
  86996. this.updateCacheCalled = false;
  86997. };
  86998. /**
  86999. * Updates the current device position and rotation in the babylon world
  87000. */
  87001. WebVRFreeCamera.prototype.update = function () {
  87002. // Get current device position in babylon world
  87003. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  87004. // Get current device rotation in babylon world
  87005. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  87006. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  87007. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  87008. _super.prototype.update.call(this);
  87009. };
  87010. /**
  87011. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  87012. * @returns an identity matrix
  87013. */
  87014. WebVRFreeCamera.prototype._getViewMatrix = function () {
  87015. return BABYLON.Matrix.Identity();
  87016. };
  87017. /**
  87018. * This function is called by the two RIG cameras.
  87019. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  87020. */
  87021. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  87022. var _this = this;
  87023. // Update the parent camera prior to using a child camera to avoid desynchronization
  87024. var parentCamera = this._cameraRigParams["parentCamera"];
  87025. parentCamera._updateCache();
  87026. //WebVR 1.1
  87027. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87028. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87029. if (!this.getScene().useRightHandedSystem) {
  87030. [2, 6, 8, 9, 14].forEach(function (num) {
  87031. _this._webvrViewMatrix.m[num] *= -1;
  87032. });
  87033. }
  87034. // update the camera rotation matrix
  87035. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87036. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87037. // Computing target and final matrix
  87038. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87039. // should the view matrix be updated with scale and position offset?
  87040. if (parentCamera.deviceScaleFactor !== 1) {
  87041. this._webvrViewMatrix.invert();
  87042. // scale the position, if set
  87043. if (parentCamera.deviceScaleFactor) {
  87044. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87045. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87046. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87047. }
  87048. this._webvrViewMatrix.invert();
  87049. }
  87050. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87051. // Compute global position
  87052. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87053. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87054. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87055. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87056. this._markSyncedWithParent();
  87057. return this._webvrViewMatrix;
  87058. };
  87059. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87060. var _this = this;
  87061. var parentCamera = this.parent;
  87062. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87063. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87064. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87065. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87066. //babylon compatible matrix
  87067. if (!this.getScene().useRightHandedSystem) {
  87068. [8, 9, 10, 11].forEach(function (num) {
  87069. _this._projectionMatrix.m[num] *= -1;
  87070. });
  87071. }
  87072. return this._projectionMatrix;
  87073. };
  87074. /**
  87075. * Initializes the controllers and their meshes
  87076. */
  87077. WebVRFreeCamera.prototype.initControllers = function () {
  87078. var _this = this;
  87079. this.controllers = [];
  87080. var manager = this.getScene().gamepadManager;
  87081. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87082. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87083. var webVrController = gamepad;
  87084. if (webVrController.defaultModel) {
  87085. webVrController.defaultModel.setEnabled(false);
  87086. }
  87087. if (webVrController.hand === "right") {
  87088. _this._rightController = null;
  87089. }
  87090. if (webVrController.hand === "left") {
  87091. _this._leftController = null;
  87092. }
  87093. var controllerIndex = _this.controllers.indexOf(webVrController);
  87094. if (controllerIndex !== -1) {
  87095. _this.controllers.splice(controllerIndex, 1);
  87096. }
  87097. }
  87098. });
  87099. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87100. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87101. var webVrController_1 = gamepad;
  87102. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87103. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87104. if (_this.webVROptions.controllerMeshes) {
  87105. if (webVrController_1.defaultModel) {
  87106. webVrController_1.defaultModel.setEnabled(true);
  87107. }
  87108. else {
  87109. // Load the meshes
  87110. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87111. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87112. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87113. if (_this.webVROptions.defaultLightingOnControllers) {
  87114. if (!_this._lightOnControllers) {
  87115. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87116. }
  87117. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87118. var children = mesh.getChildren();
  87119. if (children.length !== 0) {
  87120. children.forEach(function (mesh) {
  87121. light.includedOnlyMeshes.push(mesh);
  87122. activateLightOnSubMeshes_1(mesh, light);
  87123. });
  87124. }
  87125. };
  87126. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87127. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87128. }
  87129. });
  87130. }
  87131. }
  87132. webVrController_1.attachToPoseControlledCamera(_this);
  87133. // since this is async - sanity check. Is the controller already stored?
  87134. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87135. //add to the controllers array
  87136. _this.controllers.push(webVrController_1);
  87137. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87138. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87139. // So we're overriding setting left & right manually to be sure
  87140. var firstViveWandDetected = false;
  87141. for (var i = 0; i < _this.controllers.length; i++) {
  87142. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87143. if (!firstViveWandDetected) {
  87144. firstViveWandDetected = true;
  87145. _this.controllers[i].hand = "left";
  87146. }
  87147. else {
  87148. _this.controllers[i].hand = "right";
  87149. }
  87150. }
  87151. }
  87152. //did we find enough controllers? Great! let the developer know.
  87153. if (_this.controllers.length >= 2) {
  87154. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87155. }
  87156. }
  87157. }
  87158. });
  87159. };
  87160. return WebVRFreeCamera;
  87161. }(BABYLON.FreeCamera));
  87162. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87163. })(BABYLON || (BABYLON = {}));
  87164. //# sourceMappingURL=babylon.webVRCamera.js.map
  87165. var BABYLON;
  87166. (function (BABYLON) {
  87167. // We're mainly based on the logic defined into the FreeCamera code
  87168. /**
  87169. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87170. * being tilted forward or back and left or right.
  87171. */
  87172. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87173. __extends(DeviceOrientationCamera, _super);
  87174. /**
  87175. * Creates a new device orientation camera
  87176. * @param name The name of the camera
  87177. * @param position The start position camera
  87178. * @param scene The scene the camera belongs to
  87179. */
  87180. function DeviceOrientationCamera(name, position, scene) {
  87181. var _this = _super.call(this, name, position, scene) || this;
  87182. _this._quaternionCache = new BABYLON.Quaternion();
  87183. _this.inputs.addDeviceOrientation();
  87184. return _this;
  87185. }
  87186. /**
  87187. * Gets the current instance class name ("DeviceOrientationCamera").
  87188. * This helps avoiding instanceof at run time.
  87189. * @returns the class name
  87190. */
  87191. DeviceOrientationCamera.prototype.getClassName = function () {
  87192. return "DeviceOrientationCamera";
  87193. };
  87194. /**
  87195. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87196. */
  87197. DeviceOrientationCamera.prototype._checkInputs = function () {
  87198. _super.prototype._checkInputs.call(this);
  87199. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87200. if (this._initialQuaternion) {
  87201. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87202. }
  87203. };
  87204. /**
  87205. * Reset the camera to its default orientation on the specified axis only.
  87206. * @param axis The axis to reset
  87207. */
  87208. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87209. var _this = this;
  87210. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87211. //can only work if this camera has a rotation quaternion already.
  87212. if (!this.rotationQuaternion)
  87213. return;
  87214. if (!this._initialQuaternion) {
  87215. this._initialQuaternion = new BABYLON.Quaternion();
  87216. }
  87217. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87218. ['x', 'y', 'z'].forEach(function (axisName) {
  87219. if (!axis[axisName]) {
  87220. _this._initialQuaternion[axisName] = 0;
  87221. }
  87222. else {
  87223. _this._initialQuaternion[axisName] *= -1;
  87224. }
  87225. });
  87226. this._initialQuaternion.normalize();
  87227. //force rotation update
  87228. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87229. };
  87230. return DeviceOrientationCamera;
  87231. }(BABYLON.FreeCamera));
  87232. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87233. })(BABYLON || (BABYLON = {}));
  87234. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87235. var BABYLON;
  87236. (function (BABYLON) {
  87237. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87238. __extends(VRDeviceOrientationFreeCamera, _super);
  87239. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87240. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87241. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87242. var _this = _super.call(this, name, position, scene) || this;
  87243. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87244. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87245. return _this;
  87246. }
  87247. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87248. return "VRDeviceOrientationFreeCamera";
  87249. };
  87250. return VRDeviceOrientationFreeCamera;
  87251. }(BABYLON.DeviceOrientationCamera));
  87252. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87253. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87254. __extends(VRDeviceOrientationGamepadCamera, _super);
  87255. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87256. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87257. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87258. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87259. _this.inputs.addGamepad();
  87260. return _this;
  87261. }
  87262. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87263. return "VRDeviceOrientationGamepadCamera";
  87264. };
  87265. return VRDeviceOrientationGamepadCamera;
  87266. }(VRDeviceOrientationFreeCamera));
  87267. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87268. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87269. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87270. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87271. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87272. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87273. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87274. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87275. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87276. _this.inputs.addVRDeviceOrientation();
  87277. return _this;
  87278. }
  87279. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87280. return "VRDeviceOrientationArcRotateCamera";
  87281. };
  87282. return VRDeviceOrientationArcRotateCamera;
  87283. }(BABYLON.ArcRotateCamera));
  87284. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87285. })(BABYLON || (BABYLON = {}));
  87286. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87287. var BABYLON;
  87288. (function (BABYLON) {
  87289. /**
  87290. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87291. */
  87292. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87293. __extends(AnaglyphFreeCamera, _super);
  87294. /**
  87295. * Creates a new AnaglyphFreeCamera
  87296. * @param name defines camera name
  87297. * @param position defines initial position
  87298. * @param interaxialDistance defines distance between each color axis
  87299. * @param scene defines the hosting scene
  87300. */
  87301. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87302. var _this = _super.call(this, name, position, scene) || this;
  87303. _this.interaxialDistance = interaxialDistance;
  87304. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87305. return _this;
  87306. }
  87307. /**
  87308. * Gets camera class name
  87309. * @returns AnaglyphFreeCamera
  87310. */
  87311. AnaglyphFreeCamera.prototype.getClassName = function () {
  87312. return "AnaglyphFreeCamera";
  87313. };
  87314. return AnaglyphFreeCamera;
  87315. }(BABYLON.FreeCamera));
  87316. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87317. /**
  87318. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87319. */
  87320. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87321. __extends(AnaglyphArcRotateCamera, _super);
  87322. /**
  87323. * Creates a new AnaglyphArcRotateCamera
  87324. * @param name defines camera name
  87325. * @param alpha defines alpha angle (in radians)
  87326. * @param beta defines beta angle (in radians)
  87327. * @param radius defines radius
  87328. * @param target defines camera target
  87329. * @param interaxialDistance defines distance between each color axis
  87330. * @param scene defines the hosting scene
  87331. */
  87332. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87333. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87334. _this.interaxialDistance = interaxialDistance;
  87335. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87336. return _this;
  87337. }
  87338. /**
  87339. * Gets camera class name
  87340. * @returns AnaglyphArcRotateCamera
  87341. */
  87342. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87343. return "AnaglyphArcRotateCamera";
  87344. };
  87345. return AnaglyphArcRotateCamera;
  87346. }(BABYLON.ArcRotateCamera));
  87347. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87348. /**
  87349. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87350. */
  87351. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87352. __extends(AnaglyphGamepadCamera, _super);
  87353. /**
  87354. * Creates a new AnaglyphGamepadCamera
  87355. * @param name defines camera name
  87356. * @param position defines initial position
  87357. * @param interaxialDistance defines distance between each color axis
  87358. * @param scene defines the hosting scene
  87359. */
  87360. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87361. var _this = _super.call(this, name, position, scene) || this;
  87362. _this.interaxialDistance = interaxialDistance;
  87363. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87364. return _this;
  87365. }
  87366. /**
  87367. * Gets camera class name
  87368. * @returns AnaglyphGamepadCamera
  87369. */
  87370. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87371. return "AnaglyphGamepadCamera";
  87372. };
  87373. return AnaglyphGamepadCamera;
  87374. }(BABYLON.GamepadCamera));
  87375. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87376. /**
  87377. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87378. */
  87379. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87380. __extends(AnaglyphUniversalCamera, _super);
  87381. /**
  87382. * Creates a new AnaglyphUniversalCamera
  87383. * @param name defines camera name
  87384. * @param position defines initial position
  87385. * @param interaxialDistance defines distance between each color axis
  87386. * @param scene defines the hosting scene
  87387. */
  87388. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87389. var _this = _super.call(this, name, position, scene) || this;
  87390. _this.interaxialDistance = interaxialDistance;
  87391. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87392. return _this;
  87393. }
  87394. /**
  87395. * Gets camera class name
  87396. * @returns AnaglyphUniversalCamera
  87397. */
  87398. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87399. return "AnaglyphUniversalCamera";
  87400. };
  87401. return AnaglyphUniversalCamera;
  87402. }(BABYLON.UniversalCamera));
  87403. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87404. /**
  87405. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87406. */
  87407. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87408. __extends(StereoscopicFreeCamera, _super);
  87409. /**
  87410. * Creates a new StereoscopicFreeCamera
  87411. * @param name defines camera name
  87412. * @param position defines initial position
  87413. * @param interaxialDistance defines distance between each color axis
  87414. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87415. * @param scene defines the hosting scene
  87416. */
  87417. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87418. var _this = _super.call(this, name, position, scene) || this;
  87419. _this.interaxialDistance = interaxialDistance;
  87420. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87421. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87422. return _this;
  87423. }
  87424. /**
  87425. * Gets camera class name
  87426. * @returns StereoscopicFreeCamera
  87427. */
  87428. StereoscopicFreeCamera.prototype.getClassName = function () {
  87429. return "StereoscopicFreeCamera";
  87430. };
  87431. return StereoscopicFreeCamera;
  87432. }(BABYLON.FreeCamera));
  87433. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87434. /**
  87435. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87436. */
  87437. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87438. __extends(StereoscopicArcRotateCamera, _super);
  87439. /**
  87440. * Creates a new StereoscopicArcRotateCamera
  87441. * @param name defines camera name
  87442. * @param alpha defines alpha angle (in radians)
  87443. * @param beta defines beta angle (in radians)
  87444. * @param radius defines radius
  87445. * @param target defines camera target
  87446. * @param interaxialDistance defines distance between each color axis
  87447. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87448. * @param scene defines the hosting scene
  87449. */
  87450. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87451. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87452. _this.interaxialDistance = interaxialDistance;
  87453. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87454. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87455. return _this;
  87456. }
  87457. /**
  87458. * Gets camera class name
  87459. * @returns StereoscopicArcRotateCamera
  87460. */
  87461. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87462. return "StereoscopicArcRotateCamera";
  87463. };
  87464. return StereoscopicArcRotateCamera;
  87465. }(BABYLON.ArcRotateCamera));
  87466. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87467. /**
  87468. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87469. */
  87470. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87471. __extends(StereoscopicGamepadCamera, _super);
  87472. /**
  87473. * Creates a new StereoscopicGamepadCamera
  87474. * @param name defines camera name
  87475. * @param position defines initial position
  87476. * @param interaxialDistance defines distance between each color axis
  87477. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87478. * @param scene defines the hosting scene
  87479. */
  87480. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87481. var _this = _super.call(this, name, position, scene) || this;
  87482. _this.interaxialDistance = interaxialDistance;
  87483. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87484. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87485. return _this;
  87486. }
  87487. /**
  87488. * Gets camera class name
  87489. * @returns StereoscopicGamepadCamera
  87490. */
  87491. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87492. return "StereoscopicGamepadCamera";
  87493. };
  87494. return StereoscopicGamepadCamera;
  87495. }(BABYLON.GamepadCamera));
  87496. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87497. /**
  87498. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87499. */
  87500. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87501. __extends(StereoscopicUniversalCamera, _super);
  87502. /**
  87503. * Creates a new StereoscopicUniversalCamera
  87504. * @param name defines camera name
  87505. * @param position defines initial position
  87506. * @param interaxialDistance defines distance between each color axis
  87507. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87508. * @param scene defines the hosting scene
  87509. */
  87510. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87511. var _this = _super.call(this, name, position, scene) || this;
  87512. _this.interaxialDistance = interaxialDistance;
  87513. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87514. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87515. return _this;
  87516. }
  87517. /**
  87518. * Gets camera class name
  87519. * @returns StereoscopicUniversalCamera
  87520. */
  87521. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87522. return "StereoscopicUniversalCamera";
  87523. };
  87524. return StereoscopicUniversalCamera;
  87525. }(BABYLON.UniversalCamera));
  87526. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87527. })(BABYLON || (BABYLON = {}));
  87528. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87529. var BABYLON;
  87530. (function (BABYLON) {
  87531. var VRExperienceHelperGazer = /** @class */ (function () {
  87532. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87533. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87534. this.scene = scene;
  87535. this._pointerDownOnMeshAsked = false;
  87536. this._isActionableMesh = false;
  87537. this._teleportationRequestInitiated = false;
  87538. this._teleportationBackRequestInitiated = false;
  87539. this._rotationRightAsked = false;
  87540. this._rotationLeftAsked = false;
  87541. this._dpadPressed = true;
  87542. this._activePointer = false;
  87543. this._id = VRExperienceHelperGazer._idCounter++;
  87544. // Gaze tracker
  87545. if (!gazeTrackerToClone) {
  87546. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87547. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87548. this._gazeTracker.isPickable = false;
  87549. this._gazeTracker.isVisible = false;
  87550. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87551. targetMat.specularColor = BABYLON.Color3.Black();
  87552. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87553. targetMat.backFaceCulling = false;
  87554. this._gazeTracker.material = targetMat;
  87555. }
  87556. else {
  87557. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87558. }
  87559. }
  87560. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87561. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87562. };
  87563. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87564. this._pointerDownOnMeshAsked = true;
  87565. if (this._currentMeshSelected && this._currentHit) {
  87566. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87567. }
  87568. };
  87569. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87570. if (this._currentMeshSelected && this._currentHit) {
  87571. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87572. }
  87573. this._pointerDownOnMeshAsked = false;
  87574. };
  87575. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87576. this._activePointer = true;
  87577. };
  87578. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87579. this._activePointer = false;
  87580. };
  87581. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87582. if (distance === void 0) { distance = 100; }
  87583. };
  87584. VRExperienceHelperGazer.prototype.dispose = function () {
  87585. this._interactionsEnabled = false;
  87586. this._teleportationEnabled = false;
  87587. if (this._gazeTracker) {
  87588. this._gazeTracker.dispose();
  87589. }
  87590. };
  87591. VRExperienceHelperGazer._idCounter = 0;
  87592. return VRExperienceHelperGazer;
  87593. }());
  87594. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87595. __extends(VRExperienceHelperControllerGazer, _super);
  87596. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87597. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87598. _this.webVRController = webVRController;
  87599. // Laser pointer
  87600. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87601. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87602. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87603. laserPointerMaterial.alpha = 0.6;
  87604. _this._laserPointer.material = laserPointerMaterial;
  87605. _this._laserPointer.rotation.x = Math.PI / 2;
  87606. _this._laserPointer.position.z = -0.5;
  87607. _this._laserPointer.isVisible = false;
  87608. if (!webVRController.mesh) {
  87609. // Create an empty mesh that is used prior to loading the high quality model
  87610. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87611. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87612. preloadPointerPose.rotation.x = -0.7;
  87613. preloadMesh.addChild(preloadPointerPose);
  87614. webVRController.attachToMesh(preloadMesh);
  87615. }
  87616. _this._setLaserPointerParent(webVRController.mesh);
  87617. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87618. _this._setLaserPointerParent(mesh);
  87619. });
  87620. return _this;
  87621. }
  87622. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87623. return this.webVRController.getForwardRay(length);
  87624. };
  87625. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87626. _super.prototype._activatePointer.call(this);
  87627. this._laserPointer.isVisible = true;
  87628. };
  87629. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87630. _super.prototype._deactivatePointer.call(this);
  87631. this._laserPointer.isVisible = false;
  87632. };
  87633. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87634. this._laserPointer.material.emissiveColor = color;
  87635. };
  87636. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87637. var makeNotPick = function (root) {
  87638. root.name += " laserPointer";
  87639. root.getChildMeshes().forEach(function (c) {
  87640. makeNotPick(c);
  87641. });
  87642. };
  87643. makeNotPick(mesh);
  87644. var childMeshes = mesh.getChildMeshes();
  87645. this.webVRController._pointingPoseNode = null;
  87646. for (var i = 0; i < childMeshes.length; i++) {
  87647. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87648. mesh = childMeshes[i];
  87649. this.webVRController._pointingPoseNode = mesh;
  87650. break;
  87651. }
  87652. }
  87653. this._laserPointer.parent = mesh;
  87654. };
  87655. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87656. if (distance === void 0) { distance = 100; }
  87657. this._laserPointer.scaling.y = distance;
  87658. this._laserPointer.position.z = -distance / 2;
  87659. };
  87660. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87661. _super.prototype.dispose.call(this);
  87662. this._laserPointer.dispose();
  87663. if (this._meshAttachedObserver) {
  87664. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87665. }
  87666. };
  87667. return VRExperienceHelperControllerGazer;
  87668. }(VRExperienceHelperGazer));
  87669. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87670. __extends(VRExperienceHelperCameraGazer, _super);
  87671. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87672. var _this = _super.call(this, scene) || this;
  87673. _this.getCamera = getCamera;
  87674. return _this;
  87675. }
  87676. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87677. var camera = this.getCamera();
  87678. if (camera) {
  87679. return camera.getForwardRay(length);
  87680. }
  87681. else {
  87682. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87683. }
  87684. };
  87685. return VRExperienceHelperCameraGazer;
  87686. }(VRExperienceHelperGazer));
  87687. /**
  87688. * Helps to quickly add VR support to an existing scene.
  87689. * See http://doc.babylonjs.com/how_to/webvr_helper
  87690. */
  87691. var VRExperienceHelper = /** @class */ (function () {
  87692. /**
  87693. * Instantiates a VRExperienceHelper.
  87694. * Helps to quickly add VR support to an existing scene.
  87695. * @param scene The scene the VRExperienceHelper belongs to.
  87696. * @param webVROptions Options to modify the vr experience helper's behavior.
  87697. */
  87698. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87699. if (webVROptions === void 0) { webVROptions = {}; }
  87700. var _this = this;
  87701. this.webVROptions = webVROptions;
  87702. // Can the system support WebVR, even if a headset isn't plugged in?
  87703. this._webVRsupported = false;
  87704. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87705. this._webVRready = false;
  87706. // Are we waiting for the requestPresent callback to complete?
  87707. this._webVRrequesting = false;
  87708. // Are we presenting to the headset right now?
  87709. this._webVRpresenting = false;
  87710. // Are we presenting in the fullscreen fallback?
  87711. this._fullscreenVRpresenting = false;
  87712. /**
  87713. * Observable raised when entering VR.
  87714. */
  87715. this.onEnteringVRObservable = new BABYLON.Observable();
  87716. /**
  87717. * Observable raised when exiting VR.
  87718. */
  87719. this.onExitingVRObservable = new BABYLON.Observable();
  87720. /**
  87721. * Observable raised when controller mesh is loaded.
  87722. */
  87723. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87724. this._useCustomVRButton = false;
  87725. this._teleportationRequested = false;
  87726. this._teleportActive = false;
  87727. this._floorMeshesCollection = [];
  87728. this._rotationAllowed = true;
  87729. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87730. this._isDefaultTeleportationTarget = true;
  87731. this._teleportationFillColor = "#444444";
  87732. this._teleportationBorderColor = "#FFFFFF";
  87733. this._rotationAngle = 0;
  87734. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87735. this._padSensibilityUp = 0.65;
  87736. this._padSensibilityDown = 0.35;
  87737. this.leftController = null;
  87738. this.rightController = null;
  87739. /**
  87740. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87741. */
  87742. this.onNewMeshSelected = new BABYLON.Observable();
  87743. /**
  87744. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87745. */
  87746. this.onNewMeshPicked = new BABYLON.Observable();
  87747. /**
  87748. * Observable raised before camera teleportation
  87749. */
  87750. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87751. /**
  87752. * Observable raised after camera teleportation
  87753. */
  87754. this.onAfterCameraTeleport = new BABYLON.Observable();
  87755. /**
  87756. * Observable raised when current selected mesh gets unselected
  87757. */
  87758. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87759. /**
  87760. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87761. */
  87762. this.teleportationEnabled = true;
  87763. this._teleportationInitialized = false;
  87764. this._interactionsEnabled = false;
  87765. this._interactionsRequested = false;
  87766. this._displayGaze = true;
  87767. this._displayLaserPointer = true;
  87768. this._onResize = function () {
  87769. _this.moveButtonToBottomRight();
  87770. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87771. _this.exitVR();
  87772. }
  87773. };
  87774. this._onFullscreenChange = function () {
  87775. if (document.fullscreen !== undefined) {
  87776. _this._fullscreenVRpresenting = document.fullscreen;
  87777. }
  87778. else if (document.mozFullScreen !== undefined) {
  87779. _this._fullscreenVRpresenting = document.mozFullScreen;
  87780. }
  87781. else if (document.webkitIsFullScreen !== undefined) {
  87782. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87783. }
  87784. else if (document.msIsFullScreen !== undefined) {
  87785. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87786. }
  87787. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87788. _this.exitVR();
  87789. if (!_this._useCustomVRButton) {
  87790. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87791. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87792. }
  87793. }
  87794. };
  87795. this.beforeRender = function () {
  87796. if (_this.leftController && _this.leftController._activePointer) {
  87797. _this._castRayAndSelectObject(_this.leftController);
  87798. }
  87799. if (_this.rightController && _this.rightController._activePointer) {
  87800. _this._castRayAndSelectObject(_this.rightController);
  87801. }
  87802. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87803. _this._castRayAndSelectObject(_this._cameraGazer);
  87804. }
  87805. else {
  87806. _this._cameraGazer._gazeTracker.isVisible = false;
  87807. }
  87808. };
  87809. this._onNewGamepadConnected = function (gamepad) {
  87810. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87811. if (gamepad.leftStick) {
  87812. gamepad.onleftstickchanged(function (stickValues) {
  87813. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87814. // Listening to classic/xbox gamepad only if no VR controller is active
  87815. if ((!_this.leftController && !_this.rightController) ||
  87816. ((_this.leftController && !_this.leftController._activePointer) &&
  87817. (_this.rightController && !_this.rightController._activePointer))) {
  87818. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87819. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87820. }
  87821. }
  87822. });
  87823. }
  87824. if (gamepad.rightStick) {
  87825. gamepad.onrightstickchanged(function (stickValues) {
  87826. if (_this._teleportationInitialized) {
  87827. _this._checkRotate(stickValues, _this._cameraGazer);
  87828. }
  87829. });
  87830. }
  87831. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87832. gamepad.onbuttondown(function (buttonPressed) {
  87833. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87834. _this._cameraGazer._selectionPointerDown();
  87835. }
  87836. });
  87837. gamepad.onbuttonup(function (buttonPressed) {
  87838. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87839. _this._cameraGazer._selectionPointerUp();
  87840. }
  87841. });
  87842. }
  87843. }
  87844. else {
  87845. var webVRController = gamepad;
  87846. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87847. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87848. _this.rightController = controller;
  87849. }
  87850. else {
  87851. _this.leftController = controller;
  87852. }
  87853. _this._tryEnableInteractionOnController(controller);
  87854. }
  87855. };
  87856. // 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
  87857. this._tryEnableInteractionOnController = function (controller) {
  87858. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87859. _this._enableInteractionOnController(controller);
  87860. }
  87861. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87862. _this._enableTeleportationOnController(controller);
  87863. }
  87864. };
  87865. this._onNewGamepadDisconnected = function (gamepad) {
  87866. if (gamepad instanceof BABYLON.WebVRController) {
  87867. if (gamepad.hand === "left" && _this.leftController != null) {
  87868. _this.leftController.dispose();
  87869. _this.leftController = null;
  87870. }
  87871. if (gamepad.hand === "right" && _this.rightController != null) {
  87872. _this.rightController.dispose();
  87873. _this.rightController = null;
  87874. }
  87875. }
  87876. };
  87877. this._workingVector = BABYLON.Vector3.Zero();
  87878. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87879. this._workingMatrix = BABYLON.Matrix.Identity();
  87880. this._scene = scene;
  87881. this._canvas = scene.getEngine().getRenderingCanvas();
  87882. // Parse options
  87883. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87884. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87885. }
  87886. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87887. webVROptions.createDeviceOrientationCamera = true;
  87888. }
  87889. if (webVROptions.defaultHeight === undefined) {
  87890. webVROptions.defaultHeight = 1.7;
  87891. }
  87892. if (webVROptions.useCustomVRButton) {
  87893. this._useCustomVRButton = true;
  87894. if (webVROptions.customVRButton) {
  87895. this._btnVR = webVROptions.customVRButton;
  87896. }
  87897. }
  87898. if (webVROptions.rayLength) {
  87899. this._rayLength = webVROptions.rayLength;
  87900. }
  87901. this._defaultHeight = webVROptions.defaultHeight;
  87902. if (webVROptions.positionScale) {
  87903. this._rayLength *= webVROptions.positionScale;
  87904. this._defaultHeight *= webVROptions.positionScale;
  87905. }
  87906. // Set position
  87907. if (this._scene.activeCamera) {
  87908. this._position = this._scene.activeCamera.position.clone();
  87909. }
  87910. else {
  87911. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87912. }
  87913. // Set non-vr camera
  87914. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87915. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87916. // Copy data from existing camera
  87917. if (this._scene.activeCamera) {
  87918. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87919. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87920. // Set rotation from previous camera
  87921. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87922. var targetCamera = this._scene.activeCamera;
  87923. if (targetCamera.rotationQuaternion) {
  87924. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87925. }
  87926. else {
  87927. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87928. }
  87929. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87930. }
  87931. }
  87932. this._scene.activeCamera = this._deviceOrientationCamera;
  87933. if (this._canvas) {
  87934. this._scene.activeCamera.attachControl(this._canvas);
  87935. }
  87936. }
  87937. else {
  87938. this._existingCamera = this._scene.activeCamera;
  87939. }
  87940. // Create VR cameras
  87941. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87942. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87943. }
  87944. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87945. this._webVRCamera.useStandingMatrix();
  87946. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87947. // Create default button
  87948. if (!this._useCustomVRButton) {
  87949. this._btnVR = document.createElement("BUTTON");
  87950. this._btnVR.className = "babylonVRicon";
  87951. this._btnVR.id = "babylonVRiconbtn";
  87952. this._btnVR.title = "Click to switch to VR";
  87953. 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) }";
  87954. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87955. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87956. // css += ".babylonVRicon.vrdisplaysupported { }";
  87957. // css += ".babylonVRicon.vrdisplayready { }";
  87958. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87959. var style = document.createElement('style');
  87960. style.appendChild(document.createTextNode(css));
  87961. document.getElementsByTagName('head')[0].appendChild(style);
  87962. this.moveButtonToBottomRight();
  87963. }
  87964. // VR button click event
  87965. if (this._btnVR) {
  87966. this._btnVR.addEventListener("click", function () {
  87967. if (!_this.isInVRMode) {
  87968. _this.enterVR();
  87969. }
  87970. else {
  87971. _this.exitVR();
  87972. }
  87973. });
  87974. }
  87975. // Window events
  87976. window.addEventListener("resize", this._onResize);
  87977. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87978. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87979. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87980. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87981. // Display vr button when headset is connected
  87982. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87983. this.displayVRButton();
  87984. }
  87985. else {
  87986. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87987. if (e.vrDisplay) {
  87988. _this.displayVRButton();
  87989. }
  87990. });
  87991. }
  87992. // Exiting VR mode using 'ESC' key on desktop
  87993. this._onKeyDown = function (event) {
  87994. if (event.keyCode === 27 && _this.isInVRMode) {
  87995. _this.exitVR();
  87996. }
  87997. };
  87998. document.addEventListener("keydown", this._onKeyDown);
  87999. // Exiting VR mode double tapping the touch screen
  88000. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  88001. if (_this.isInVRMode) {
  88002. _this.exitVR();
  88003. if (_this._fullscreenVRpresenting) {
  88004. _this._scene.getEngine().switchFullscreen(true);
  88005. }
  88006. }
  88007. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  88008. // Listen for WebVR display changes
  88009. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  88010. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  88011. this._onVRRequestPresentStart = function () {
  88012. _this._webVRrequesting = true;
  88013. _this.updateButtonVisibility();
  88014. };
  88015. this._onVRRequestPresentComplete = function (success) {
  88016. _this._webVRrequesting = false;
  88017. _this.updateButtonVisibility();
  88018. };
  88019. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  88020. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  88021. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  88022. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88023. scene.onDisposeObservable.add(function () {
  88024. _this.dispose();
  88025. });
  88026. // Gamepad connection events
  88027. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88028. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88029. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88030. this.updateButtonVisibility();
  88031. //create easing functions
  88032. this._circleEase = new BABYLON.CircleEase();
  88033. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88034. }
  88035. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88036. /** Return this.onEnteringVRObservable
  88037. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88038. */
  88039. get: function () {
  88040. return this.onEnteringVRObservable;
  88041. },
  88042. enumerable: true,
  88043. configurable: true
  88044. });
  88045. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88046. /** Return this.onExitingVRObservable
  88047. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88048. */
  88049. get: function () {
  88050. return this.onExitingVRObservable;
  88051. },
  88052. enumerable: true,
  88053. configurable: true
  88054. });
  88055. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88056. /** Return this.onControllerMeshLoadedObservable
  88057. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88058. */
  88059. get: function () {
  88060. return this.onControllerMeshLoadedObservable;
  88061. },
  88062. enumerable: true,
  88063. configurable: true
  88064. });
  88065. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88066. /**
  88067. * The mesh used to display where the user is going to teleport.
  88068. */
  88069. get: function () {
  88070. return this._teleportationTarget;
  88071. },
  88072. /**
  88073. * Sets the mesh to be used to display where the user is going to teleport.
  88074. */
  88075. set: function (value) {
  88076. if (value) {
  88077. value.name = "teleportationTarget";
  88078. this._isDefaultTeleportationTarget = false;
  88079. this._teleportationTarget = value;
  88080. }
  88081. },
  88082. enumerable: true,
  88083. configurable: true
  88084. });
  88085. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88086. /**
  88087. * The mesh used to display where the user is selecting,
  88088. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88089. * See http://doc.babylonjs.com/resources/baking_transformations
  88090. */
  88091. get: function () {
  88092. return this._cameraGazer._gazeTracker;
  88093. },
  88094. set: function (value) {
  88095. if (value) {
  88096. this._cameraGazer._gazeTracker = value;
  88097. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88098. this._cameraGazer._gazeTracker.isPickable = false;
  88099. this._cameraGazer._gazeTracker.isVisible = false;
  88100. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88101. if (this.leftController) {
  88102. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88103. }
  88104. if (this.rightController) {
  88105. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88106. }
  88107. }
  88108. },
  88109. enumerable: true,
  88110. configurable: true
  88111. });
  88112. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88113. /**
  88114. * If the ray of the gaze should be displayed.
  88115. */
  88116. get: function () {
  88117. return this._displayGaze;
  88118. },
  88119. /**
  88120. * Sets if the ray of the gaze should be displayed.
  88121. */
  88122. set: function (value) {
  88123. this._displayGaze = value;
  88124. if (!value) {
  88125. this._cameraGazer._gazeTracker.isVisible = false;
  88126. if (this.leftController) {
  88127. this.leftController._gazeTracker.isVisible = false;
  88128. }
  88129. if (this.rightController) {
  88130. this.rightController._gazeTracker.isVisible = false;
  88131. }
  88132. }
  88133. },
  88134. enumerable: true,
  88135. configurable: true
  88136. });
  88137. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88138. /**
  88139. * If the ray of the LaserPointer should be displayed.
  88140. */
  88141. get: function () {
  88142. return this._displayLaserPointer;
  88143. },
  88144. /**
  88145. * Sets if the ray of the LaserPointer should be displayed.
  88146. */
  88147. set: function (value) {
  88148. this._displayLaserPointer = value;
  88149. if (!value) {
  88150. if (this.rightController) {
  88151. this.rightController._deactivatePointer();
  88152. this.rightController._gazeTracker.isVisible = false;
  88153. }
  88154. if (this.leftController) {
  88155. this.leftController._deactivatePointer();
  88156. this.leftController._gazeTracker.isVisible = false;
  88157. }
  88158. }
  88159. else {
  88160. if (this.rightController) {
  88161. this.rightController._activatePointer();
  88162. }
  88163. if (this.leftController) {
  88164. this.leftController._activatePointer();
  88165. }
  88166. }
  88167. },
  88168. enumerable: true,
  88169. configurable: true
  88170. });
  88171. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88172. /**
  88173. * The deviceOrientationCamera used as the camera when not in VR.
  88174. */
  88175. get: function () {
  88176. return this._deviceOrientationCamera;
  88177. },
  88178. enumerable: true,
  88179. configurable: true
  88180. });
  88181. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88182. /**
  88183. * Based on the current WebVR support, returns the current VR camera used.
  88184. */
  88185. get: function () {
  88186. if (this._webVRready) {
  88187. return this._webVRCamera;
  88188. }
  88189. else {
  88190. return this._scene.activeCamera;
  88191. }
  88192. },
  88193. enumerable: true,
  88194. configurable: true
  88195. });
  88196. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88197. /**
  88198. * The webVRCamera which is used when in VR.
  88199. */
  88200. get: function () {
  88201. return this._webVRCamera;
  88202. },
  88203. enumerable: true,
  88204. configurable: true
  88205. });
  88206. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88207. /**
  88208. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88209. */
  88210. get: function () {
  88211. return this._vrDeviceOrientationCamera;
  88212. },
  88213. enumerable: true,
  88214. configurable: true
  88215. });
  88216. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88217. get: function () {
  88218. var result = this._cameraGazer._teleportationRequestInitiated
  88219. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88220. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88221. return result;
  88222. },
  88223. enumerable: true,
  88224. configurable: true
  88225. });
  88226. // Raised when one of the controller has loaded successfully its associated default mesh
  88227. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88228. if (this.leftController && this.leftController.webVRController == webVRController) {
  88229. if (webVRController.mesh) {
  88230. this.leftController._setLaserPointerParent(webVRController.mesh);
  88231. }
  88232. }
  88233. if (this.rightController && this.rightController.webVRController == webVRController) {
  88234. if (webVRController.mesh) {
  88235. this.rightController._setLaserPointerParent(webVRController.mesh);
  88236. }
  88237. }
  88238. try {
  88239. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88240. }
  88241. catch (err) {
  88242. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88243. }
  88244. };
  88245. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88246. /**
  88247. * Gets a value indicating if we are currently in VR mode.
  88248. */
  88249. get: function () {
  88250. return this._webVRpresenting || this._fullscreenVRpresenting;
  88251. },
  88252. enumerable: true,
  88253. configurable: true
  88254. });
  88255. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88256. var vrDisplay = this._scene.getEngine().getVRDevice();
  88257. if (vrDisplay) {
  88258. var wasPresenting = this._webVRpresenting;
  88259. // A VR display is connected
  88260. this._webVRpresenting = vrDisplay.isPresenting;
  88261. if (wasPresenting && !this._webVRpresenting)
  88262. this.exitVR();
  88263. }
  88264. else {
  88265. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88266. }
  88267. this.updateButtonVisibility();
  88268. };
  88269. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88270. this._webVRsupported = eventArgs.vrSupported;
  88271. this._webVRready = !!eventArgs.vrDisplay;
  88272. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88273. this.updateButtonVisibility();
  88274. };
  88275. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88276. if (this._canvas && !this._useCustomVRButton) {
  88277. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88278. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88279. }
  88280. };
  88281. VRExperienceHelper.prototype.displayVRButton = function () {
  88282. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88283. document.body.appendChild(this._btnVR);
  88284. this._btnVRDisplayed = true;
  88285. }
  88286. };
  88287. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88288. if (!this._btnVR || this._useCustomVRButton) {
  88289. return;
  88290. }
  88291. this._btnVR.className = "babylonVRicon";
  88292. if (this.isInVRMode) {
  88293. this._btnVR.className += " vrdisplaypresenting";
  88294. }
  88295. else {
  88296. if (this._webVRready)
  88297. this._btnVR.className += " vrdisplayready";
  88298. if (this._webVRsupported)
  88299. this._btnVR.className += " vrdisplaysupported";
  88300. if (this._webVRrequesting)
  88301. this._btnVR.className += " vrdisplayrequesting";
  88302. }
  88303. };
  88304. /**
  88305. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88306. * Otherwise, will use the fullscreen API.
  88307. */
  88308. VRExperienceHelper.prototype.enterVR = function () {
  88309. if (this.onEnteringVRObservable) {
  88310. try {
  88311. this.onEnteringVRObservable.notifyObservers(this);
  88312. }
  88313. catch (err) {
  88314. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88315. }
  88316. }
  88317. if (this._scene.activeCamera) {
  88318. this._position = this._scene.activeCamera.position.clone();
  88319. // make sure that we return to the last active camera
  88320. this._existingCamera = this._scene.activeCamera;
  88321. }
  88322. if (this._webVRrequesting)
  88323. return;
  88324. // If WebVR is supported and a headset is connected
  88325. if (this._webVRready) {
  88326. if (!this._webVRpresenting) {
  88327. this._webVRCamera.position = this._position;
  88328. this._scene.activeCamera = this._webVRCamera;
  88329. }
  88330. }
  88331. else if (this._vrDeviceOrientationCamera) {
  88332. this._vrDeviceOrientationCamera.position = this._position;
  88333. if (this._scene.activeCamera) {
  88334. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88335. }
  88336. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88337. this._scene.getEngine().switchFullscreen(true);
  88338. this.updateButtonVisibility();
  88339. }
  88340. if (this._scene.activeCamera && this._canvas) {
  88341. this._scene.activeCamera.attachControl(this._canvas);
  88342. }
  88343. if (this._interactionsEnabled) {
  88344. this._scene.registerBeforeRender(this.beforeRender);
  88345. }
  88346. };
  88347. /**
  88348. * Attempt to exit VR, or fullscreen.
  88349. */
  88350. VRExperienceHelper.prototype.exitVR = function () {
  88351. if (this.onExitingVRObservable) {
  88352. try {
  88353. this.onExitingVRObservable.notifyObservers(this);
  88354. }
  88355. catch (err) {
  88356. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88357. }
  88358. }
  88359. if (this._webVRpresenting) {
  88360. this._scene.getEngine().disableVR();
  88361. }
  88362. if (this._scene.activeCamera) {
  88363. this._position = this._scene.activeCamera.position.clone();
  88364. }
  88365. if (this._deviceOrientationCamera) {
  88366. this._deviceOrientationCamera.position = this._position;
  88367. this._scene.activeCamera = this._deviceOrientationCamera;
  88368. if (this._canvas) {
  88369. this._scene.activeCamera.attachControl(this._canvas);
  88370. }
  88371. }
  88372. else if (this._existingCamera) {
  88373. this._existingCamera.position = this._position;
  88374. this._scene.activeCamera = this._existingCamera;
  88375. }
  88376. this.updateButtonVisibility();
  88377. if (this._interactionsEnabled) {
  88378. this._scene.unregisterBeforeRender(this.beforeRender);
  88379. }
  88380. // resize to update width and height when exiting vr exits fullscreen
  88381. this._scene.getEngine().resize();
  88382. };
  88383. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88384. /**
  88385. * The position of the vr experience helper.
  88386. */
  88387. get: function () {
  88388. return this._position;
  88389. },
  88390. /**
  88391. * Sets the position of the vr experience helper.
  88392. */
  88393. set: function (value) {
  88394. this._position = value;
  88395. if (this._scene.activeCamera) {
  88396. this._scene.activeCamera.position = value;
  88397. }
  88398. },
  88399. enumerable: true,
  88400. configurable: true
  88401. });
  88402. /**
  88403. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88404. */
  88405. VRExperienceHelper.prototype.enableInteractions = function () {
  88406. var _this = this;
  88407. if (!this._interactionsEnabled) {
  88408. this._interactionsRequested = true;
  88409. if (this.leftController) {
  88410. this._enableInteractionOnController(this.leftController);
  88411. }
  88412. if (this.rightController) {
  88413. this._enableInteractionOnController(this.rightController);
  88414. }
  88415. this.raySelectionPredicate = function (mesh) {
  88416. return mesh.isVisible;
  88417. };
  88418. this.meshSelectionPredicate = function (mesh) {
  88419. return true;
  88420. };
  88421. this._raySelectionPredicate = function (mesh) {
  88422. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88423. && mesh.name.indexOf("teleportationTarget") === -1
  88424. && mesh.name.indexOf("torusTeleportation") === -1
  88425. && mesh.name.indexOf("laserPointer") === -1)) {
  88426. return _this.raySelectionPredicate(mesh);
  88427. }
  88428. return false;
  88429. };
  88430. this._interactionsEnabled = true;
  88431. }
  88432. };
  88433. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88434. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88435. if (this._floorMeshesCollection[i].id === mesh.id) {
  88436. return true;
  88437. }
  88438. }
  88439. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88440. return true;
  88441. }
  88442. return false;
  88443. };
  88444. /**
  88445. * Adds a floor mesh to be used for teleportation.
  88446. * @param floorMesh the mesh to be used for teleportation.
  88447. */
  88448. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88449. if (!this._floorMeshesCollection) {
  88450. return;
  88451. }
  88452. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88453. return;
  88454. }
  88455. this._floorMeshesCollection.push(floorMesh);
  88456. };
  88457. /**
  88458. * Removes a floor mesh from being used for teleportation.
  88459. * @param floorMesh the mesh to be removed.
  88460. */
  88461. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88462. if (!this._floorMeshesCollection) {
  88463. return;
  88464. }
  88465. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88466. if (meshIndex !== -1) {
  88467. this._floorMeshesCollection.splice(meshIndex, 1);
  88468. }
  88469. };
  88470. /**
  88471. * Enables interactions and teleportation using the VR controllers and gaze.
  88472. * @param vrTeleportationOptions options to modify teleportation behavior.
  88473. */
  88474. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88475. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88476. if (!this._teleportationInitialized) {
  88477. this._teleportationRequested = true;
  88478. this.enableInteractions();
  88479. if (vrTeleportationOptions.floorMeshName) {
  88480. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88481. }
  88482. if (vrTeleportationOptions.floorMeshes) {
  88483. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88484. }
  88485. if (this.leftController != null) {
  88486. this._enableTeleportationOnController(this.leftController);
  88487. }
  88488. if (this.rightController != null) {
  88489. this._enableTeleportationOnController(this.rightController);
  88490. }
  88491. // Creates an image processing post process for the vignette not relying
  88492. // on the main scene configuration for image processing to reduce setup and spaces
  88493. // (gamma/linear) conflicts.
  88494. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88495. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88496. imageProcessingConfiguration.vignetteEnabled = true;
  88497. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88498. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88499. this._teleportationInitialized = true;
  88500. if (this._isDefaultTeleportationTarget) {
  88501. this._createTeleportationCircles();
  88502. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88503. }
  88504. }
  88505. };
  88506. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88507. var _this = this;
  88508. var controllerMesh = controller.webVRController.mesh;
  88509. if (controllerMesh) {
  88510. controller._interactionsEnabled = true;
  88511. controller._activatePointer();
  88512. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88513. // Enabling / disabling laserPointer
  88514. if (_this._displayLaserPointer && stateObject.value === 1) {
  88515. if (controller._activePointer) {
  88516. controller._deactivatePointer();
  88517. }
  88518. else {
  88519. controller._activatePointer();
  88520. }
  88521. if (_this.displayGaze) {
  88522. controller._gazeTracker.isVisible = controller._activePointer;
  88523. }
  88524. }
  88525. });
  88526. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88527. if (!controller._pointerDownOnMeshAsked) {
  88528. if (stateObject.value > _this._padSensibilityUp) {
  88529. controller._selectionPointerDown();
  88530. }
  88531. }
  88532. else if (stateObject.value < _this._padSensibilityDown) {
  88533. controller._selectionPointerUp();
  88534. }
  88535. });
  88536. }
  88537. };
  88538. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88539. // Dont teleport if another gaze already requested teleportation
  88540. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88541. return;
  88542. }
  88543. if (!gazer._teleportationRequestInitiated) {
  88544. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88545. gazer._activatePointer();
  88546. gazer._teleportationRequestInitiated = true;
  88547. }
  88548. }
  88549. else {
  88550. // Listening to the proper controller values changes to confirm teleportation
  88551. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88552. if (this._teleportActive) {
  88553. this._teleportCamera(this._haloCenter);
  88554. }
  88555. gazer._teleportationRequestInitiated = false;
  88556. }
  88557. }
  88558. };
  88559. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88560. // Only rotate when user is not currently selecting a teleportation location
  88561. if (gazer._teleportationRequestInitiated) {
  88562. return;
  88563. }
  88564. if (!gazer._rotationLeftAsked) {
  88565. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88566. gazer._rotationLeftAsked = true;
  88567. if (this._rotationAllowed) {
  88568. this._rotateCamera(false);
  88569. }
  88570. }
  88571. }
  88572. else {
  88573. if (stateObject.x > -this._padSensibilityDown) {
  88574. gazer._rotationLeftAsked = false;
  88575. }
  88576. }
  88577. if (!gazer._rotationRightAsked) {
  88578. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88579. gazer._rotationRightAsked = true;
  88580. if (this._rotationAllowed) {
  88581. this._rotateCamera(true);
  88582. }
  88583. }
  88584. }
  88585. else {
  88586. if (stateObject.x < this._padSensibilityDown) {
  88587. gazer._rotationRightAsked = false;
  88588. }
  88589. }
  88590. };
  88591. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88592. // Only teleport backwards when user is not currently selecting a teleportation location
  88593. if (gazer._teleportationRequestInitiated) {
  88594. return;
  88595. }
  88596. // Teleport backwards
  88597. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88598. if (!gazer._teleportationBackRequestInitiated) {
  88599. if (!this.currentVRCamera) {
  88600. return;
  88601. }
  88602. // Get rotation and position of the current camera
  88603. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88604. var position = this.currentVRCamera.position;
  88605. // If the camera has device position, use that instead
  88606. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88607. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88608. position = this.currentVRCamera.devicePosition;
  88609. }
  88610. // Get matrix with only the y rotation of the device rotation
  88611. rotation.toEulerAnglesToRef(this._workingVector);
  88612. this._workingVector.z = 0;
  88613. this._workingVector.x = 0;
  88614. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88615. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88616. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88617. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88618. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88619. var ray = new BABYLON.Ray(position, this._workingVector);
  88620. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88621. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88622. this._teleportCamera(hit.pickedPoint);
  88623. }
  88624. gazer._teleportationBackRequestInitiated = true;
  88625. }
  88626. }
  88627. else {
  88628. gazer._teleportationBackRequestInitiated = false;
  88629. }
  88630. };
  88631. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88632. var _this = this;
  88633. var controllerMesh = controller.webVRController.mesh;
  88634. if (controllerMesh) {
  88635. if (!controller._interactionsEnabled) {
  88636. this._enableInteractionOnController(controller);
  88637. }
  88638. controller._interactionsEnabled = true;
  88639. controller._teleportationEnabled = true;
  88640. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88641. controller._dpadPressed = false;
  88642. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88643. controller._dpadPressed = stateObject.pressed;
  88644. if (!controller._dpadPressed) {
  88645. controller._rotationLeftAsked = false;
  88646. controller._rotationRightAsked = false;
  88647. controller._teleportationBackRequestInitiated = false;
  88648. }
  88649. });
  88650. }
  88651. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88652. if (_this.teleportationEnabled) {
  88653. _this._checkTeleportBackwards(stateObject, controller);
  88654. _this._checkTeleportWithRay(stateObject, controller);
  88655. }
  88656. _this._checkRotate(stateObject, controller);
  88657. });
  88658. }
  88659. };
  88660. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88661. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88662. this._teleportationTarget.isPickable = false;
  88663. var length = 512;
  88664. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88665. dynamicTexture.hasAlpha = true;
  88666. var context = dynamicTexture.getContext();
  88667. var centerX = length / 2;
  88668. var centerY = length / 2;
  88669. var radius = 200;
  88670. context.beginPath();
  88671. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88672. context.fillStyle = this._teleportationFillColor;
  88673. context.fill();
  88674. context.lineWidth = 10;
  88675. context.strokeStyle = this._teleportationBorderColor;
  88676. context.stroke();
  88677. context.closePath();
  88678. dynamicTexture.update();
  88679. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88680. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88681. this._teleportationTarget.material = teleportationCircleMaterial;
  88682. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88683. torus.isPickable = false;
  88684. torus.parent = this._teleportationTarget;
  88685. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88686. var keys = [];
  88687. keys.push({
  88688. frame: 0,
  88689. value: 0
  88690. });
  88691. keys.push({
  88692. frame: 30,
  88693. value: 0.4
  88694. });
  88695. keys.push({
  88696. frame: 60,
  88697. value: 0
  88698. });
  88699. animationInnerCircle.setKeys(keys);
  88700. var easingFunction = new BABYLON.SineEase();
  88701. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88702. animationInnerCircle.setEasingFunction(easingFunction);
  88703. torus.animations = [];
  88704. torus.animations.push(animationInnerCircle);
  88705. this._scene.beginAnimation(torus, 0, 60, true);
  88706. this._hideTeleportationTarget();
  88707. };
  88708. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88709. this._teleportActive = true;
  88710. if (this._teleportationInitialized) {
  88711. this._teleportationTarget.isVisible = true;
  88712. if (this._isDefaultTeleportationTarget) {
  88713. this._teleportationTarget.getChildren()[0].isVisible = true;
  88714. }
  88715. }
  88716. };
  88717. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88718. this._teleportActive = false;
  88719. if (this._teleportationInitialized) {
  88720. this._teleportationTarget.isVisible = false;
  88721. if (this._isDefaultTeleportationTarget) {
  88722. this._teleportationTarget.getChildren()[0].isVisible = false;
  88723. }
  88724. }
  88725. };
  88726. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88727. var _this = this;
  88728. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88729. return;
  88730. }
  88731. if (right) {
  88732. this._rotationAngle++;
  88733. }
  88734. else {
  88735. this._rotationAngle--;
  88736. }
  88737. this.currentVRCamera.animations = [];
  88738. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88739. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88740. var animationRotationKeys = [];
  88741. animationRotationKeys.push({
  88742. frame: 0,
  88743. value: this.currentVRCamera.rotationQuaternion
  88744. });
  88745. animationRotationKeys.push({
  88746. frame: 6,
  88747. value: target
  88748. });
  88749. animationRotation.setKeys(animationRotationKeys);
  88750. animationRotation.setEasingFunction(this._circleEase);
  88751. this.currentVRCamera.animations.push(animationRotation);
  88752. this._postProcessMove.animations = [];
  88753. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88754. var vignetteWeightKeys = [];
  88755. vignetteWeightKeys.push({
  88756. frame: 0,
  88757. value: 0
  88758. });
  88759. vignetteWeightKeys.push({
  88760. frame: 3,
  88761. value: 4
  88762. });
  88763. vignetteWeightKeys.push({
  88764. frame: 6,
  88765. value: 0
  88766. });
  88767. animationPP.setKeys(vignetteWeightKeys);
  88768. animationPP.setEasingFunction(this._circleEase);
  88769. this._postProcessMove.animations.push(animationPP);
  88770. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88771. var vignetteStretchKeys = [];
  88772. vignetteStretchKeys.push({
  88773. frame: 0,
  88774. value: 0
  88775. });
  88776. vignetteStretchKeys.push({
  88777. frame: 3,
  88778. value: 10
  88779. });
  88780. vignetteStretchKeys.push({
  88781. frame: 6,
  88782. value: 0
  88783. });
  88784. animationPP2.setKeys(vignetteStretchKeys);
  88785. animationPP2.setEasingFunction(this._circleEase);
  88786. this._postProcessMove.animations.push(animationPP2);
  88787. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88788. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88789. this._postProcessMove.samples = 4;
  88790. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88791. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88792. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88793. });
  88794. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88795. };
  88796. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88797. if (hit.pickedPoint) {
  88798. if (gazer._teleportationRequestInitiated) {
  88799. this._displayTeleportationTarget();
  88800. this._haloCenter.copyFrom(hit.pickedPoint);
  88801. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88802. }
  88803. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88804. if (pickNormal) {
  88805. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88806. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88807. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88808. }
  88809. this._teleportationTarget.position.y += 0.1;
  88810. }
  88811. };
  88812. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88813. var _this = this;
  88814. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88815. return;
  88816. }
  88817. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88818. // offset of the headset from the anchor.
  88819. if (this.webVRCamera.leftCamera) {
  88820. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88821. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88822. location.subtractToRef(this._workingVector, this._workingVector);
  88823. }
  88824. else {
  88825. this._workingVector.copyFrom(location);
  88826. }
  88827. // Add height to account for user's height offset
  88828. if (this.isInVRMode) {
  88829. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88830. }
  88831. else {
  88832. this._workingVector.y += this._defaultHeight;
  88833. }
  88834. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88835. // Create animation from the camera's position to the new location
  88836. this.currentVRCamera.animations = [];
  88837. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88838. var animationCameraTeleportationKeys = [{
  88839. frame: 0,
  88840. value: this.currentVRCamera.position
  88841. },
  88842. {
  88843. frame: 11,
  88844. value: this._workingVector
  88845. }
  88846. ];
  88847. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88848. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88849. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88850. this._postProcessMove.animations = [];
  88851. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88852. var vignetteWeightKeys = [];
  88853. vignetteWeightKeys.push({
  88854. frame: 0,
  88855. value: 0
  88856. });
  88857. vignetteWeightKeys.push({
  88858. frame: 5,
  88859. value: 8
  88860. });
  88861. vignetteWeightKeys.push({
  88862. frame: 11,
  88863. value: 0
  88864. });
  88865. animationPP.setKeys(vignetteWeightKeys);
  88866. this._postProcessMove.animations.push(animationPP);
  88867. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88868. var vignetteStretchKeys = [];
  88869. vignetteStretchKeys.push({
  88870. frame: 0,
  88871. value: 0
  88872. });
  88873. vignetteStretchKeys.push({
  88874. frame: 5,
  88875. value: 10
  88876. });
  88877. vignetteStretchKeys.push({
  88878. frame: 11,
  88879. value: 0
  88880. });
  88881. animationPP2.setKeys(vignetteStretchKeys);
  88882. this._postProcessMove.animations.push(animationPP2);
  88883. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88884. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88885. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88886. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88887. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88888. });
  88889. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88890. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88891. });
  88892. this._hideTeleportationTarget();
  88893. };
  88894. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88895. if (normal) {
  88896. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88897. if (angle < Math.PI / 2) {
  88898. normal.scaleInPlace(-1);
  88899. }
  88900. }
  88901. return normal;
  88902. };
  88903. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88904. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88905. return;
  88906. }
  88907. var ray = gazer._getForwardRay(this._rayLength);
  88908. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88909. // Moving the gazeTracker on the mesh face targetted
  88910. if (hit && hit.pickedPoint) {
  88911. if (this._displayGaze) {
  88912. var multiplier = 1;
  88913. gazer._gazeTracker.isVisible = true;
  88914. if (gazer._isActionableMesh) {
  88915. multiplier = 3;
  88916. }
  88917. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88918. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88919. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88920. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88921. // To avoid z-fighting
  88922. var deltaFighting = 0.002;
  88923. if (pickNormal) {
  88924. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88925. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88926. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88927. }
  88928. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88929. if (gazer._gazeTracker.position.x < 0) {
  88930. gazer._gazeTracker.position.x += deltaFighting;
  88931. }
  88932. else {
  88933. gazer._gazeTracker.position.x -= deltaFighting;
  88934. }
  88935. if (gazer._gazeTracker.position.y < 0) {
  88936. gazer._gazeTracker.position.y += deltaFighting;
  88937. }
  88938. else {
  88939. gazer._gazeTracker.position.y -= deltaFighting;
  88940. }
  88941. if (gazer._gazeTracker.position.z < 0) {
  88942. gazer._gazeTracker.position.z += deltaFighting;
  88943. }
  88944. else {
  88945. gazer._gazeTracker.position.z -= deltaFighting;
  88946. }
  88947. }
  88948. // Changing the size of the laser pointer based on the distance from the targetted point
  88949. gazer._updatePointerDistance(hit.distance);
  88950. }
  88951. else {
  88952. gazer._updatePointerDistance();
  88953. gazer._gazeTracker.isVisible = false;
  88954. }
  88955. if (hit && hit.pickedMesh) {
  88956. gazer._currentHit = hit;
  88957. if (gazer._pointerDownOnMeshAsked) {
  88958. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88959. }
  88960. // The object selected is the floor, we're in a teleportation scenario
  88961. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88962. // Moving the teleportation area to this targetted point
  88963. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88964. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88965. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88966. }
  88967. gazer._currentMeshSelected = null;
  88968. if (gazer._teleportationRequestInitiated) {
  88969. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88970. }
  88971. return;
  88972. }
  88973. // If not, we're in a selection scenario
  88974. //this._teleportationAllowed = false;
  88975. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88976. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88977. this.onNewMeshPicked.notifyObservers(hit);
  88978. gazer._currentMeshSelected = hit.pickedMesh;
  88979. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88980. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88981. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88982. gazer._isActionableMesh = true;
  88983. }
  88984. else {
  88985. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88986. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88987. gazer._isActionableMesh = false;
  88988. }
  88989. try {
  88990. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88991. }
  88992. catch (err) {
  88993. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88994. }
  88995. }
  88996. else {
  88997. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88998. gazer._currentMeshSelected = null;
  88999. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89000. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89001. }
  89002. }
  89003. }
  89004. else {
  89005. gazer._currentHit = null;
  89006. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  89007. gazer._currentMeshSelected = null;
  89008. //this._teleportationAllowed = false;
  89009. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89010. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  89011. }
  89012. };
  89013. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  89014. if (mesh) {
  89015. this.onSelectedMeshUnselected.notifyObservers(mesh);
  89016. }
  89017. };
  89018. /**
  89019. * Sets the color of the laser ray from the vr controllers.
  89020. * @param color new color for the ray.
  89021. */
  89022. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  89023. if (this.leftController) {
  89024. this.leftController._setLaserPointerColor(color);
  89025. }
  89026. if (this.rightController) {
  89027. this.rightController._setLaserPointerColor(color);
  89028. }
  89029. };
  89030. /**
  89031. * Sets the color of the ray from the vr headsets gaze.
  89032. * @param color new color for the ray.
  89033. */
  89034. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89035. if (!this._cameraGazer._gazeTracker.material) {
  89036. return;
  89037. }
  89038. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89039. if (this.leftController) {
  89040. this.leftController._gazeTracker.material.emissiveColor = color;
  89041. }
  89042. if (this.rightController) {
  89043. this.rightController._gazeTracker.material.emissiveColor = color;
  89044. }
  89045. };
  89046. /**
  89047. * Exits VR and disposes of the vr experience helper
  89048. */
  89049. VRExperienceHelper.prototype.dispose = function () {
  89050. if (this.isInVRMode) {
  89051. this.exitVR();
  89052. }
  89053. if (this._postProcessMove) {
  89054. this._postProcessMove.dispose();
  89055. }
  89056. if (this._webVRCamera) {
  89057. this._webVRCamera.dispose();
  89058. }
  89059. if (this._vrDeviceOrientationCamera) {
  89060. this._vrDeviceOrientationCamera.dispose();
  89061. }
  89062. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89063. document.body.removeChild(this._btnVR);
  89064. }
  89065. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89066. this._deviceOrientationCamera.dispose();
  89067. }
  89068. if (this._cameraGazer) {
  89069. this._cameraGazer.dispose();
  89070. }
  89071. if (this.leftController) {
  89072. this.leftController.dispose();
  89073. }
  89074. if (this.rightController) {
  89075. this.rightController.dispose();
  89076. }
  89077. if (this._teleportationTarget) {
  89078. this._teleportationTarget.dispose();
  89079. }
  89080. this._floorMeshesCollection = [];
  89081. document.removeEventListener("keydown", this._onKeyDown);
  89082. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89083. window.removeEventListener("resize", this._onResize);
  89084. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89085. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89086. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89087. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89088. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89089. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89090. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89091. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89092. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89093. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89094. this._scene.unregisterBeforeRender(this.beforeRender);
  89095. };
  89096. /**
  89097. * Gets the name of the VRExperienceHelper class
  89098. * @returns "VRExperienceHelper"
  89099. */
  89100. VRExperienceHelper.prototype.getClassName = function () {
  89101. return "VRExperienceHelper";
  89102. };
  89103. return VRExperienceHelper;
  89104. }());
  89105. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89106. })(BABYLON || (BABYLON = {}));
  89107. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89108. // Mainly based on these 2 articles :
  89109. // 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
  89110. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89111. var BABYLON;
  89112. (function (BABYLON) {
  89113. /**
  89114. * Defines the potential axis of a Joystick
  89115. */
  89116. var JoystickAxis;
  89117. (function (JoystickAxis) {
  89118. /** X axis */
  89119. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89120. /** Y axis */
  89121. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89122. /** Z axis */
  89123. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89124. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89125. /**
  89126. * Class used to define virtual joystick (used in touch mode)
  89127. */
  89128. var VirtualJoystick = /** @class */ (function () {
  89129. /**
  89130. * Creates a new virtual joystick
  89131. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89132. */
  89133. function VirtualJoystick(leftJoystick) {
  89134. var _this = this;
  89135. if (leftJoystick) {
  89136. this._leftJoystick = true;
  89137. }
  89138. else {
  89139. this._leftJoystick = false;
  89140. }
  89141. VirtualJoystick._globalJoystickIndex++;
  89142. // By default left & right arrow keys are moving the X
  89143. // and up & down keys are moving the Y
  89144. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89145. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89146. this.reverseLeftRight = false;
  89147. this.reverseUpDown = false;
  89148. // collections of pointers
  89149. this._touches = new BABYLON.StringDictionary();
  89150. this.deltaPosition = BABYLON.Vector3.Zero();
  89151. this._joystickSensibility = 25;
  89152. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89153. this._onResize = function (evt) {
  89154. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89155. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89156. if (VirtualJoystick.vjCanvas) {
  89157. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89158. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89159. }
  89160. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89161. };
  89162. // injecting a canvas element on top of the canvas 3D game
  89163. if (!VirtualJoystick.vjCanvas) {
  89164. window.addEventListener("resize", this._onResize, false);
  89165. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89166. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89167. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89168. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89169. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89170. VirtualJoystick.vjCanvas.style.width = "100%";
  89171. VirtualJoystick.vjCanvas.style.height = "100%";
  89172. VirtualJoystick.vjCanvas.style.position = "absolute";
  89173. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89174. VirtualJoystick.vjCanvas.style.top = "0px";
  89175. VirtualJoystick.vjCanvas.style.left = "0px";
  89176. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89177. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89178. // Support for jQuery PEP polyfill
  89179. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89180. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89181. if (!context) {
  89182. throw new Error("Unable to create canvas for virtual joystick");
  89183. }
  89184. VirtualJoystick.vjCanvasContext = context;
  89185. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89186. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89187. document.body.appendChild(VirtualJoystick.vjCanvas);
  89188. }
  89189. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89190. this.pressed = false;
  89191. // default joystick color
  89192. this._joystickColor = "cyan";
  89193. this._joystickPointerID = -1;
  89194. // current joystick position
  89195. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89196. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89197. // origin joystick position
  89198. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89199. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89200. this._onPointerDownHandlerRef = function (evt) {
  89201. _this._onPointerDown(evt);
  89202. };
  89203. this._onPointerMoveHandlerRef = function (evt) {
  89204. _this._onPointerMove(evt);
  89205. };
  89206. this._onPointerUpHandlerRef = function (evt) {
  89207. _this._onPointerUp(evt);
  89208. };
  89209. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89210. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89211. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89212. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89213. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89214. evt.preventDefault(); // Disables system menu
  89215. }, false);
  89216. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89217. }
  89218. /**
  89219. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89220. * @param newJoystickSensibility defines the new sensibility
  89221. */
  89222. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89223. this._joystickSensibility = newJoystickSensibility;
  89224. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89225. };
  89226. VirtualJoystick.prototype._onPointerDown = function (e) {
  89227. var positionOnScreenCondition;
  89228. e.preventDefault();
  89229. if (this._leftJoystick === true) {
  89230. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89231. }
  89232. else {
  89233. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89234. }
  89235. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89236. // First contact will be dedicated to the virtual joystick
  89237. this._joystickPointerID = e.pointerId;
  89238. this._joystickPointerStartPos.x = e.clientX;
  89239. this._joystickPointerStartPos.y = e.clientY;
  89240. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89241. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89242. this._deltaJoystickVector.x = 0;
  89243. this._deltaJoystickVector.y = 0;
  89244. this.pressed = true;
  89245. this._touches.add(e.pointerId.toString(), e);
  89246. }
  89247. else {
  89248. // You can only trigger the action buttons with a joystick declared
  89249. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89250. this._action();
  89251. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89252. }
  89253. }
  89254. };
  89255. VirtualJoystick.prototype._onPointerMove = function (e) {
  89256. // If the current pointer is the one associated to the joystick (first touch contact)
  89257. if (this._joystickPointerID == e.pointerId) {
  89258. this._joystickPointerPos.x = e.clientX;
  89259. this._joystickPointerPos.y = e.clientY;
  89260. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89261. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89262. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89263. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89264. switch (this._axisTargetedByLeftAndRight) {
  89265. case JoystickAxis.X:
  89266. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89267. break;
  89268. case JoystickAxis.Y:
  89269. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89270. break;
  89271. case JoystickAxis.Z:
  89272. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89273. break;
  89274. }
  89275. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89276. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89277. switch (this._axisTargetedByUpAndDown) {
  89278. case JoystickAxis.X:
  89279. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89280. break;
  89281. case JoystickAxis.Y:
  89282. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89283. break;
  89284. case JoystickAxis.Z:
  89285. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89286. break;
  89287. }
  89288. }
  89289. else {
  89290. var data = this._touches.get(e.pointerId.toString());
  89291. if (data) {
  89292. data.x = e.clientX;
  89293. data.y = e.clientY;
  89294. }
  89295. }
  89296. };
  89297. VirtualJoystick.prototype._onPointerUp = function (e) {
  89298. if (this._joystickPointerID == e.pointerId) {
  89299. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89300. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89301. this._joystickPointerID = -1;
  89302. this.pressed = false;
  89303. }
  89304. else {
  89305. var touch = this._touches.get(e.pointerId.toString());
  89306. if (touch) {
  89307. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89308. }
  89309. }
  89310. this._deltaJoystickVector.x = 0;
  89311. this._deltaJoystickVector.y = 0;
  89312. this._touches.remove(e.pointerId.toString());
  89313. };
  89314. /**
  89315. * Change the color of the virtual joystick
  89316. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89317. */
  89318. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89319. this._joystickColor = newColor;
  89320. };
  89321. /**
  89322. * Defines a callback to call when the joystick is touched
  89323. * @param action defines the callback
  89324. */
  89325. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89326. this._action = action;
  89327. };
  89328. /**
  89329. * Defines which axis you'd like to control for left & right
  89330. * @param axis defines the axis to use
  89331. */
  89332. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89333. switch (axis) {
  89334. case JoystickAxis.X:
  89335. case JoystickAxis.Y:
  89336. case JoystickAxis.Z:
  89337. this._axisTargetedByLeftAndRight = axis;
  89338. break;
  89339. default:
  89340. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89341. break;
  89342. }
  89343. };
  89344. /**
  89345. * Defines which axis you'd like to control for up & down
  89346. * @param axis defines the axis to use
  89347. */
  89348. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89349. switch (axis) {
  89350. case JoystickAxis.X:
  89351. case JoystickAxis.Y:
  89352. case JoystickAxis.Z:
  89353. this._axisTargetedByUpAndDown = axis;
  89354. break;
  89355. default:
  89356. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89357. break;
  89358. }
  89359. };
  89360. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89361. var _this = this;
  89362. if (this.pressed) {
  89363. this._touches.forEach(function (key, touch) {
  89364. if (touch.pointerId === _this._joystickPointerID) {
  89365. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89366. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89367. VirtualJoystick.vjCanvasContext.beginPath();
  89368. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89369. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89370. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89371. VirtualJoystick.vjCanvasContext.stroke();
  89372. VirtualJoystick.vjCanvasContext.closePath();
  89373. VirtualJoystick.vjCanvasContext.beginPath();
  89374. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89375. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89376. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89377. VirtualJoystick.vjCanvasContext.stroke();
  89378. VirtualJoystick.vjCanvasContext.closePath();
  89379. VirtualJoystick.vjCanvasContext.beginPath();
  89380. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89381. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89382. VirtualJoystick.vjCanvasContext.stroke();
  89383. VirtualJoystick.vjCanvasContext.closePath();
  89384. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89385. }
  89386. else {
  89387. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89388. VirtualJoystick.vjCanvasContext.beginPath();
  89389. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89390. VirtualJoystick.vjCanvasContext.beginPath();
  89391. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89392. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89393. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89394. VirtualJoystick.vjCanvasContext.stroke();
  89395. VirtualJoystick.vjCanvasContext.closePath();
  89396. touch.prevX = touch.x;
  89397. touch.prevY = touch.y;
  89398. }
  89399. ;
  89400. });
  89401. }
  89402. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89403. };
  89404. /**
  89405. * Release internal HTML canvas
  89406. */
  89407. VirtualJoystick.prototype.releaseCanvas = function () {
  89408. if (VirtualJoystick.vjCanvas) {
  89409. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89410. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89411. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89412. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89413. window.removeEventListener("resize", this._onResize);
  89414. document.body.removeChild(VirtualJoystick.vjCanvas);
  89415. VirtualJoystick.vjCanvas = null;
  89416. }
  89417. };
  89418. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89419. VirtualJoystick._globalJoystickIndex = 0;
  89420. return VirtualJoystick;
  89421. }());
  89422. BABYLON.VirtualJoystick = VirtualJoystick;
  89423. })(BABYLON || (BABYLON = {}));
  89424. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89425. var BABYLON;
  89426. (function (BABYLON) {
  89427. // We're mainly based on the logic defined into the FreeCamera code
  89428. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89429. __extends(VirtualJoysticksCamera, _super);
  89430. function VirtualJoysticksCamera(name, position, scene) {
  89431. var _this = _super.call(this, name, position, scene) || this;
  89432. _this.inputs.addVirtualJoystick();
  89433. return _this;
  89434. }
  89435. VirtualJoysticksCamera.prototype.getClassName = function () {
  89436. return "VirtualJoysticksCamera";
  89437. };
  89438. return VirtualJoysticksCamera;
  89439. }(BABYLON.FreeCamera));
  89440. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89441. })(BABYLON || (BABYLON = {}));
  89442. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89443. var BABYLON;
  89444. (function (BABYLON) {
  89445. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89446. function FreeCameraVirtualJoystickInput() {
  89447. }
  89448. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89449. return this._leftjoystick;
  89450. };
  89451. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89452. return this._rightjoystick;
  89453. };
  89454. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89455. if (this._leftjoystick) {
  89456. var camera = this.camera;
  89457. var speed = camera._computeLocalCameraSpeed() * 50;
  89458. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89459. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89460. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89461. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89462. if (!this._leftjoystick.pressed) {
  89463. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89464. }
  89465. if (!this._rightjoystick.pressed) {
  89466. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89467. }
  89468. }
  89469. };
  89470. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89471. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89472. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89473. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89474. this._leftjoystick.setJoystickSensibility(0.15);
  89475. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89476. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89477. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89478. this._rightjoystick.reverseUpDown = true;
  89479. this._rightjoystick.setJoystickSensibility(0.05);
  89480. this._rightjoystick.setJoystickColor("yellow");
  89481. };
  89482. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89483. this._leftjoystick.releaseCanvas();
  89484. this._rightjoystick.releaseCanvas();
  89485. };
  89486. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89487. return "FreeCameraVirtualJoystickInput";
  89488. };
  89489. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89490. return "virtualJoystick";
  89491. };
  89492. return FreeCameraVirtualJoystickInput;
  89493. }());
  89494. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89495. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89496. })(BABYLON || (BABYLON = {}));
  89497. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89498. var BABYLON;
  89499. (function (BABYLON) {
  89500. var SimplificationSettings = /** @class */ (function () {
  89501. function SimplificationSettings(quality, distance, optimizeMesh) {
  89502. this.quality = quality;
  89503. this.distance = distance;
  89504. this.optimizeMesh = optimizeMesh;
  89505. }
  89506. return SimplificationSettings;
  89507. }());
  89508. BABYLON.SimplificationSettings = SimplificationSettings;
  89509. var SimplificationQueue = /** @class */ (function () {
  89510. function SimplificationQueue() {
  89511. this.running = false;
  89512. this._simplificationArray = [];
  89513. }
  89514. SimplificationQueue.prototype.addTask = function (task) {
  89515. this._simplificationArray.push(task);
  89516. };
  89517. SimplificationQueue.prototype.executeNext = function () {
  89518. var task = this._simplificationArray.pop();
  89519. if (task) {
  89520. this.running = true;
  89521. this.runSimplification(task);
  89522. }
  89523. else {
  89524. this.running = false;
  89525. }
  89526. };
  89527. SimplificationQueue.prototype.runSimplification = function (task) {
  89528. var _this = this;
  89529. if (task.parallelProcessing) {
  89530. //parallel simplifier
  89531. task.settings.forEach(function (setting) {
  89532. var simplifier = _this.getSimplifier(task);
  89533. simplifier.simplify(setting, function (newMesh) {
  89534. task.mesh.addLODLevel(setting.distance, newMesh);
  89535. newMesh.isVisible = true;
  89536. //check if it is the last
  89537. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89538. //all done, run the success callback.
  89539. task.successCallback();
  89540. }
  89541. _this.executeNext();
  89542. });
  89543. });
  89544. }
  89545. else {
  89546. //single simplifier.
  89547. var simplifier = this.getSimplifier(task);
  89548. var runDecimation = function (setting, callback) {
  89549. simplifier.simplify(setting, function (newMesh) {
  89550. task.mesh.addLODLevel(setting.distance, newMesh);
  89551. newMesh.isVisible = true;
  89552. //run the next quality level
  89553. callback();
  89554. });
  89555. };
  89556. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89557. runDecimation(task.settings[loop.index], function () {
  89558. loop.executeNext();
  89559. });
  89560. }, function () {
  89561. //execution ended, run the success callback.
  89562. if (task.successCallback) {
  89563. task.successCallback();
  89564. }
  89565. _this.executeNext();
  89566. });
  89567. }
  89568. };
  89569. SimplificationQueue.prototype.getSimplifier = function (task) {
  89570. switch (task.simplificationType) {
  89571. case SimplificationType.QUADRATIC:
  89572. default:
  89573. return new QuadraticErrorSimplification(task.mesh);
  89574. }
  89575. };
  89576. return SimplificationQueue;
  89577. }());
  89578. BABYLON.SimplificationQueue = SimplificationQueue;
  89579. /**
  89580. * The implemented types of simplification
  89581. * At the moment only Quadratic Error Decimation is implemented
  89582. */
  89583. var SimplificationType;
  89584. (function (SimplificationType) {
  89585. /** Quadratic error decimation */
  89586. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89587. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89588. var DecimationTriangle = /** @class */ (function () {
  89589. function DecimationTriangle(vertices) {
  89590. this.vertices = vertices;
  89591. this.error = new Array(4);
  89592. this.deleted = false;
  89593. this.isDirty = false;
  89594. this.deletePending = false;
  89595. this.borderFactor = 0;
  89596. }
  89597. return DecimationTriangle;
  89598. }());
  89599. BABYLON.DecimationTriangle = DecimationTriangle;
  89600. var DecimationVertex = /** @class */ (function () {
  89601. function DecimationVertex(position, id) {
  89602. this.position = position;
  89603. this.id = id;
  89604. this.isBorder = true;
  89605. this.q = new QuadraticMatrix();
  89606. this.triangleCount = 0;
  89607. this.triangleStart = 0;
  89608. this.originalOffsets = [];
  89609. }
  89610. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89611. this.position.copyFrom(newPosition);
  89612. };
  89613. return DecimationVertex;
  89614. }());
  89615. BABYLON.DecimationVertex = DecimationVertex;
  89616. var QuadraticMatrix = /** @class */ (function () {
  89617. function QuadraticMatrix(data) {
  89618. this.data = new Array(10);
  89619. for (var i = 0; i < 10; ++i) {
  89620. if (data && data[i]) {
  89621. this.data[i] = data[i];
  89622. }
  89623. else {
  89624. this.data[i] = 0;
  89625. }
  89626. }
  89627. }
  89628. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89629. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89630. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89631. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89632. return det;
  89633. };
  89634. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89635. for (var i = 0; i < 10; ++i) {
  89636. this.data[i] += matrix.data[i];
  89637. }
  89638. };
  89639. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89640. for (var i = 0; i < 10; ++i) {
  89641. this.data[i] += data[i];
  89642. }
  89643. };
  89644. QuadraticMatrix.prototype.add = function (matrix) {
  89645. var m = new QuadraticMatrix();
  89646. for (var i = 0; i < 10; ++i) {
  89647. m.data[i] = this.data[i] + matrix.data[i];
  89648. }
  89649. return m;
  89650. };
  89651. QuadraticMatrix.FromData = function (a, b, c, d) {
  89652. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89653. };
  89654. //returning an array to avoid garbage collection
  89655. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89656. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89657. };
  89658. return QuadraticMatrix;
  89659. }());
  89660. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89661. var Reference = /** @class */ (function () {
  89662. function Reference(vertexId, triangleId) {
  89663. this.vertexId = vertexId;
  89664. this.triangleId = triangleId;
  89665. }
  89666. return Reference;
  89667. }());
  89668. BABYLON.Reference = Reference;
  89669. /**
  89670. * An implementation of the Quadratic Error simplification algorithm.
  89671. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89672. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89673. * @author RaananW
  89674. */
  89675. var QuadraticErrorSimplification = /** @class */ (function () {
  89676. function QuadraticErrorSimplification(_mesh) {
  89677. this._mesh = _mesh;
  89678. this.syncIterations = 5000;
  89679. this.aggressiveness = 7;
  89680. this.decimationIterations = 100;
  89681. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89682. }
  89683. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89684. var _this = this;
  89685. this.initDecimatedMesh();
  89686. //iterating through the submeshes array, one after the other.
  89687. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89688. _this.initWithMesh(loop.index, function () {
  89689. _this.runDecimation(settings, loop.index, function () {
  89690. loop.executeNext();
  89691. });
  89692. }, settings.optimizeMesh);
  89693. }, function () {
  89694. setTimeout(function () {
  89695. successCallback(_this._reconstructedMesh);
  89696. }, 0);
  89697. });
  89698. };
  89699. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89700. var _this = this;
  89701. var targetCount = ~~(this.triangles.length * settings.quality);
  89702. var deletedTriangles = 0;
  89703. var triangleCount = this.triangles.length;
  89704. var iterationFunction = function (iteration, callback) {
  89705. setTimeout(function () {
  89706. if (iteration % 5 === 0) {
  89707. _this.updateMesh(iteration === 0);
  89708. }
  89709. for (var i = 0; i < _this.triangles.length; ++i) {
  89710. _this.triangles[i].isDirty = false;
  89711. }
  89712. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89713. var trianglesIterator = function (i) {
  89714. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89715. var t = _this.triangles[tIdx];
  89716. if (!t)
  89717. return;
  89718. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89719. return;
  89720. }
  89721. for (var j = 0; j < 3; ++j) {
  89722. if (t.error[j] < threshold) {
  89723. var deleted0 = [];
  89724. var deleted1 = [];
  89725. var v0 = t.vertices[j];
  89726. var v1 = t.vertices[(j + 1) % 3];
  89727. if (v0.isBorder || v1.isBorder)
  89728. continue;
  89729. var p = BABYLON.Vector3.Zero();
  89730. var n = BABYLON.Vector3.Zero();
  89731. var uv = BABYLON.Vector2.Zero();
  89732. var color = new BABYLON.Color4(0, 0, 0, 1);
  89733. _this.calculateError(v0, v1, p, n, uv, color);
  89734. var delTr = new Array();
  89735. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89736. continue;
  89737. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89738. continue;
  89739. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89740. continue;
  89741. var uniqueArray = new Array();
  89742. delTr.forEach(function (deletedT) {
  89743. if (uniqueArray.indexOf(deletedT) === -1) {
  89744. deletedT.deletePending = true;
  89745. uniqueArray.push(deletedT);
  89746. }
  89747. });
  89748. if (uniqueArray.length % 2 !== 0) {
  89749. continue;
  89750. }
  89751. v0.q = v1.q.add(v0.q);
  89752. v0.updatePosition(p);
  89753. var tStart = _this.references.length;
  89754. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89755. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89756. var tCount = _this.references.length - tStart;
  89757. if (tCount <= v0.triangleCount) {
  89758. if (tCount) {
  89759. for (var c = 0; c < tCount; c++) {
  89760. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89761. }
  89762. }
  89763. }
  89764. else {
  89765. v0.triangleStart = tStart;
  89766. }
  89767. v0.triangleCount = tCount;
  89768. break;
  89769. }
  89770. }
  89771. };
  89772. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89773. }, 0);
  89774. };
  89775. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89776. if (triangleCount - deletedTriangles <= targetCount)
  89777. loop.breakLoop();
  89778. else {
  89779. iterationFunction(loop.index, function () {
  89780. loop.executeNext();
  89781. });
  89782. }
  89783. }, function () {
  89784. setTimeout(function () {
  89785. //reconstruct this part of the mesh
  89786. _this.reconstructMesh(submeshIndex);
  89787. successCallback();
  89788. }, 0);
  89789. });
  89790. };
  89791. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89792. var _this = this;
  89793. this.vertices = [];
  89794. this.triangles = [];
  89795. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89796. var indices = this._mesh.getIndices();
  89797. var submesh = this._mesh.subMeshes[submeshIndex];
  89798. var findInVertices = function (positionToSearch) {
  89799. if (optimizeMesh) {
  89800. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89801. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89802. return _this.vertices[ii];
  89803. }
  89804. }
  89805. }
  89806. return null;
  89807. };
  89808. var vertexReferences = [];
  89809. var vertexInit = function (i) {
  89810. if (!positionData) {
  89811. return;
  89812. }
  89813. var offset = i + submesh.verticesStart;
  89814. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89815. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89816. vertex.originalOffsets.push(offset);
  89817. if (vertex.id === _this.vertices.length) {
  89818. _this.vertices.push(vertex);
  89819. }
  89820. vertexReferences.push(vertex.id);
  89821. };
  89822. //var totalVertices = mesh.getTotalVertices();
  89823. var totalVertices = submesh.verticesCount;
  89824. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89825. var indicesInit = function (i) {
  89826. if (!indices) {
  89827. return;
  89828. }
  89829. var offset = (submesh.indexStart / 3) + i;
  89830. var pos = (offset * 3);
  89831. var i0 = indices[pos + 0];
  89832. var i1 = indices[pos + 1];
  89833. var i2 = indices[pos + 2];
  89834. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89835. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89836. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89837. var triangle = new DecimationTriangle([v0, v1, v2]);
  89838. triangle.originalOffset = pos;
  89839. _this.triangles.push(triangle);
  89840. };
  89841. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89842. _this.init(callback);
  89843. });
  89844. });
  89845. };
  89846. QuadraticErrorSimplification.prototype.init = function (callback) {
  89847. var _this = this;
  89848. var triangleInit1 = function (i) {
  89849. var t = _this.triangles[i];
  89850. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89851. for (var j = 0; j < 3; j++) {
  89852. 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))));
  89853. }
  89854. };
  89855. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89856. var triangleInit2 = function (i) {
  89857. var t = _this.triangles[i];
  89858. for (var j = 0; j < 3; ++j) {
  89859. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89860. }
  89861. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89862. };
  89863. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89864. callback();
  89865. });
  89866. });
  89867. };
  89868. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89869. var newTriangles = [];
  89870. var i;
  89871. for (i = 0; i < this.vertices.length; ++i) {
  89872. this.vertices[i].triangleCount = 0;
  89873. }
  89874. var t;
  89875. var j;
  89876. for (i = 0; i < this.triangles.length; ++i) {
  89877. if (!this.triangles[i].deleted) {
  89878. t = this.triangles[i];
  89879. for (j = 0; j < 3; ++j) {
  89880. t.vertices[j].triangleCount = 1;
  89881. }
  89882. newTriangles.push(t);
  89883. }
  89884. }
  89885. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89886. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89887. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89888. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89889. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89890. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89891. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89892. var vertexCount = 0;
  89893. for (i = 0; i < this.vertices.length; ++i) {
  89894. var vertex = this.vertices[i];
  89895. vertex.id = vertexCount;
  89896. if (vertex.triangleCount) {
  89897. vertex.originalOffsets.forEach(function (originalOffset) {
  89898. if (!normalData) {
  89899. return;
  89900. }
  89901. newPositionData.push(vertex.position.x);
  89902. newPositionData.push(vertex.position.y);
  89903. newPositionData.push(vertex.position.z);
  89904. newNormalData.push(normalData[originalOffset * 3]);
  89905. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89906. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89907. if (uvs && uvs.length) {
  89908. newUVsData.push(uvs[(originalOffset * 2)]);
  89909. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89910. }
  89911. else if (colorsData && colorsData.length) {
  89912. newColorsData.push(colorsData[(originalOffset * 4)]);
  89913. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89914. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89915. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89916. }
  89917. ++vertexCount;
  89918. });
  89919. }
  89920. }
  89921. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89922. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89923. var submeshesArray = this._reconstructedMesh.subMeshes;
  89924. this._reconstructedMesh.subMeshes = [];
  89925. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89926. var originalIndices = this._mesh.getIndices();
  89927. for (i = 0; i < newTriangles.length; ++i) {
  89928. t = newTriangles[i]; //now get the new referencing point for each vertex
  89929. [0, 1, 2].forEach(function (idx) {
  89930. var id = originalIndices[t.originalOffset + idx];
  89931. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89932. if (offset < 0)
  89933. offset = 0;
  89934. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89935. });
  89936. }
  89937. //overwriting the old vertex buffers and indices.
  89938. this._reconstructedMesh.setIndices(newIndicesArray);
  89939. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89940. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89941. if (newUVsData.length > 0)
  89942. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89943. if (newColorsData.length > 0)
  89944. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89945. //create submesh
  89946. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89947. if (submeshIndex > 0) {
  89948. this._reconstructedMesh.subMeshes = [];
  89949. submeshesArray.forEach(function (submesh) {
  89950. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89951. });
  89952. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89953. }
  89954. };
  89955. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89956. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89957. this._reconstructedMesh.material = this._mesh.material;
  89958. this._reconstructedMesh.parent = this._mesh.parent;
  89959. this._reconstructedMesh.isVisible = false;
  89960. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89961. };
  89962. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89963. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89964. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89965. if (t.deleted)
  89966. continue;
  89967. var s = this.references[vertex1.triangleStart + i].vertexId;
  89968. var v1 = t.vertices[(s + 1) % 3];
  89969. var v2 = t.vertices[(s + 2) % 3];
  89970. if ((v1 === vertex2 || v2 === vertex2)) {
  89971. deletedArray[i] = true;
  89972. delTr.push(t);
  89973. continue;
  89974. }
  89975. var d1 = v1.position.subtract(point);
  89976. d1 = d1.normalize();
  89977. var d2 = v2.position.subtract(point);
  89978. d2 = d2.normalize();
  89979. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89980. return true;
  89981. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89982. deletedArray[i] = false;
  89983. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89984. return true;
  89985. }
  89986. return false;
  89987. };
  89988. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89989. var newDeleted = deletedTriangles;
  89990. for (var i = 0; i < vertex.triangleCount; ++i) {
  89991. var ref = this.references[vertex.triangleStart + i];
  89992. var t = this.triangles[ref.triangleId];
  89993. if (t.deleted)
  89994. continue;
  89995. if (deletedArray[i] && t.deletePending) {
  89996. t.deleted = true;
  89997. newDeleted++;
  89998. continue;
  89999. }
  90000. t.vertices[ref.vertexId] = origVertex;
  90001. t.isDirty = true;
  90002. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  90003. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  90004. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  90005. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  90006. this.references.push(ref);
  90007. }
  90008. return newDeleted;
  90009. };
  90010. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  90011. for (var i = 0; i < this.vertices.length; ++i) {
  90012. var vCount = [];
  90013. var vId = [];
  90014. var v = this.vertices[i];
  90015. var j;
  90016. for (j = 0; j < v.triangleCount; ++j) {
  90017. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  90018. for (var ii = 0; ii < 3; ii++) {
  90019. var ofs = 0;
  90020. var vv = triangle.vertices[ii];
  90021. while (ofs < vCount.length) {
  90022. if (vId[ofs] === vv.id)
  90023. break;
  90024. ++ofs;
  90025. }
  90026. if (ofs === vCount.length) {
  90027. vCount.push(1);
  90028. vId.push(vv.id);
  90029. }
  90030. else {
  90031. vCount[ofs]++;
  90032. }
  90033. }
  90034. }
  90035. for (j = 0; j < vCount.length; ++j) {
  90036. if (vCount[j] === 1) {
  90037. this.vertices[vId[j]].isBorder = true;
  90038. }
  90039. else {
  90040. this.vertices[vId[j]].isBorder = false;
  90041. }
  90042. }
  90043. }
  90044. };
  90045. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90046. if (identifyBorders === void 0) { identifyBorders = false; }
  90047. var i;
  90048. if (!identifyBorders) {
  90049. var newTrianglesVector = [];
  90050. for (i = 0; i < this.triangles.length; ++i) {
  90051. if (!this.triangles[i].deleted) {
  90052. newTrianglesVector.push(this.triangles[i]);
  90053. }
  90054. }
  90055. this.triangles = newTrianglesVector;
  90056. }
  90057. for (i = 0; i < this.vertices.length; ++i) {
  90058. this.vertices[i].triangleCount = 0;
  90059. this.vertices[i].triangleStart = 0;
  90060. }
  90061. var t;
  90062. var j;
  90063. var v;
  90064. for (i = 0; i < this.triangles.length; ++i) {
  90065. t = this.triangles[i];
  90066. for (j = 0; j < 3; ++j) {
  90067. v = t.vertices[j];
  90068. v.triangleCount++;
  90069. }
  90070. }
  90071. var tStart = 0;
  90072. for (i = 0; i < this.vertices.length; ++i) {
  90073. this.vertices[i].triangleStart = tStart;
  90074. tStart += this.vertices[i].triangleCount;
  90075. this.vertices[i].triangleCount = 0;
  90076. }
  90077. var newReferences = new Array(this.triangles.length * 3);
  90078. for (i = 0; i < this.triangles.length; ++i) {
  90079. t = this.triangles[i];
  90080. for (j = 0; j < 3; ++j) {
  90081. v = t.vertices[j];
  90082. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90083. v.triangleCount++;
  90084. }
  90085. }
  90086. this.references = newReferences;
  90087. if (identifyBorders) {
  90088. this.identifyBorder();
  90089. }
  90090. };
  90091. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90092. var x = point.x;
  90093. var y = point.y;
  90094. var z = point.z;
  90095. 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
  90096. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90097. };
  90098. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90099. var q = vertex1.q.add(vertex2.q);
  90100. var border = vertex1.isBorder && vertex2.isBorder;
  90101. var error = 0;
  90102. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90103. if (qDet !== 0 && !border) {
  90104. if (!pointResult) {
  90105. pointResult = BABYLON.Vector3.Zero();
  90106. }
  90107. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90108. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90109. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90110. error = this.vertexError(q, pointResult);
  90111. }
  90112. else {
  90113. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90114. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90115. var error1 = this.vertexError(q, vertex1.position);
  90116. var error2 = this.vertexError(q, vertex2.position);
  90117. var error3 = this.vertexError(q, p3);
  90118. error = Math.min(error1, error2, error3);
  90119. if (error === error1) {
  90120. if (pointResult) {
  90121. pointResult.copyFrom(vertex1.position);
  90122. }
  90123. }
  90124. else if (error === error2) {
  90125. if (pointResult) {
  90126. pointResult.copyFrom(vertex2.position);
  90127. }
  90128. }
  90129. else {
  90130. if (pointResult) {
  90131. pointResult.copyFrom(p3);
  90132. }
  90133. }
  90134. }
  90135. return error;
  90136. };
  90137. return QuadraticErrorSimplification;
  90138. }());
  90139. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90140. })(BABYLON || (BABYLON = {}));
  90141. //# sourceMappingURL=babylon.meshSimplification.js.map
  90142. var BABYLON;
  90143. (function (BABYLON) {
  90144. var MeshLODLevel = /** @class */ (function () {
  90145. function MeshLODLevel(distance, mesh) {
  90146. this.distance = distance;
  90147. this.mesh = mesh;
  90148. }
  90149. return MeshLODLevel;
  90150. }());
  90151. BABYLON.MeshLODLevel = MeshLODLevel;
  90152. })(BABYLON || (BABYLON = {}));
  90153. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90154. var BABYLON;
  90155. (function (BABYLON) {
  90156. /**
  90157. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90158. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90159. */
  90160. var SceneOptimization = /** @class */ (function () {
  90161. /**
  90162. * Creates the SceneOptimization object
  90163. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90164. * @param desc defines the description associated with the optimization
  90165. */
  90166. function SceneOptimization(
  90167. /**
  90168. * Defines the priority of this optimization (0 by default which means first in the list)
  90169. */
  90170. priority) {
  90171. if (priority === void 0) { priority = 0; }
  90172. this.priority = priority;
  90173. }
  90174. /**
  90175. * Gets a string describing the action executed by the current optimization
  90176. * @returns description string
  90177. */
  90178. SceneOptimization.prototype.getDescription = function () {
  90179. return "";
  90180. };
  90181. /**
  90182. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90183. * @param scene defines the current scene where to apply this optimization
  90184. * @param optimizer defines the current optimizer
  90185. * @returns true if everything that can be done was applied
  90186. */
  90187. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90188. return true;
  90189. };
  90190. ;
  90191. return SceneOptimization;
  90192. }());
  90193. BABYLON.SceneOptimization = SceneOptimization;
  90194. /**
  90195. * Defines an optimization used to reduce the size of render target textures
  90196. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90197. */
  90198. var TextureOptimization = /** @class */ (function (_super) {
  90199. __extends(TextureOptimization, _super);
  90200. /**
  90201. * Creates the TextureOptimization object
  90202. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90203. * @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
  90204. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90205. */
  90206. function TextureOptimization(
  90207. /**
  90208. * Defines the priority of this optimization (0 by default which means first in the list)
  90209. */
  90210. priority,
  90211. /**
  90212. * 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
  90213. */
  90214. maximumSize,
  90215. /**
  90216. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90217. */
  90218. step) {
  90219. if (priority === void 0) { priority = 0; }
  90220. if (maximumSize === void 0) { maximumSize = 1024; }
  90221. if (step === void 0) { step = 0.5; }
  90222. var _this = _super.call(this, priority) || this;
  90223. _this.priority = priority;
  90224. _this.maximumSize = maximumSize;
  90225. _this.step = step;
  90226. return _this;
  90227. }
  90228. /**
  90229. * Gets a string describing the action executed by the current optimization
  90230. * @returns description string
  90231. */
  90232. TextureOptimization.prototype.getDescription = function () {
  90233. return "Reducing render target texture size to " + this.maximumSize;
  90234. };
  90235. /**
  90236. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90237. * @param scene defines the current scene where to apply this optimization
  90238. * @param optimizer defines the current optimizer
  90239. * @returns true if everything that can be done was applied
  90240. */
  90241. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90242. var allDone = true;
  90243. for (var index = 0; index < scene.textures.length; index++) {
  90244. var texture = scene.textures[index];
  90245. if (!texture.canRescale || texture.getContext) {
  90246. continue;
  90247. }
  90248. var currentSize = texture.getSize();
  90249. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90250. if (maxDimension > this.maximumSize) {
  90251. texture.scale(this.step);
  90252. allDone = false;
  90253. }
  90254. }
  90255. return allDone;
  90256. };
  90257. return TextureOptimization;
  90258. }(SceneOptimization));
  90259. BABYLON.TextureOptimization = TextureOptimization;
  90260. /**
  90261. * Defines an optimization used to increase or decrease the rendering resolution
  90262. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90263. */
  90264. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90265. __extends(HardwareScalingOptimization, _super);
  90266. /**
  90267. * Creates the HardwareScalingOptimization object
  90268. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90269. * @param maximumScale defines the maximum scale to use (2 by default)
  90270. * @param step defines the step to use between two passes (0.5 by default)
  90271. */
  90272. function HardwareScalingOptimization(
  90273. /**
  90274. * Defines the priority of this optimization (0 by default which means first in the list)
  90275. */
  90276. priority,
  90277. /**
  90278. * Defines the maximum scale to use (2 by default)
  90279. */
  90280. maximumScale,
  90281. /**
  90282. * Defines the step to use between two passes (0.5 by default)
  90283. */
  90284. step) {
  90285. if (priority === void 0) { priority = 0; }
  90286. if (maximumScale === void 0) { maximumScale = 2; }
  90287. if (step === void 0) { step = 0.25; }
  90288. var _this = _super.call(this, priority) || this;
  90289. _this.priority = priority;
  90290. _this.maximumScale = maximumScale;
  90291. _this.step = step;
  90292. _this._currentScale = -1;
  90293. _this._directionOffset = 1;
  90294. return _this;
  90295. }
  90296. /**
  90297. * Gets a string describing the action executed by the current optimization
  90298. * @return description string
  90299. */
  90300. HardwareScalingOptimization.prototype.getDescription = function () {
  90301. return "Setting hardware scaling level to " + this._currentScale;
  90302. };
  90303. /**
  90304. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90305. * @param scene defines the current scene where to apply this optimization
  90306. * @param optimizer defines the current optimizer
  90307. * @returns true if everything that can be done was applied
  90308. */
  90309. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90310. if (this._currentScale === -1) {
  90311. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90312. if (this._currentScale > this.maximumScale) {
  90313. this._directionOffset = -1;
  90314. }
  90315. }
  90316. this._currentScale += this._directionOffset * this.step;
  90317. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90318. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90319. };
  90320. ;
  90321. return HardwareScalingOptimization;
  90322. }(SceneOptimization));
  90323. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90324. /**
  90325. * Defines an optimization used to remove shadows
  90326. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90327. */
  90328. var ShadowsOptimization = /** @class */ (function (_super) {
  90329. __extends(ShadowsOptimization, _super);
  90330. function ShadowsOptimization() {
  90331. return _super !== null && _super.apply(this, arguments) || this;
  90332. }
  90333. /**
  90334. * Gets a string describing the action executed by the current optimization
  90335. * @return description string
  90336. */
  90337. ShadowsOptimization.prototype.getDescription = function () {
  90338. return "Turning shadows on/off";
  90339. };
  90340. /**
  90341. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90342. * @param scene defines the current scene where to apply this optimization
  90343. * @param optimizer defines the current optimizer
  90344. * @returns true if everything that can be done was applied
  90345. */
  90346. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90347. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90348. return true;
  90349. };
  90350. ;
  90351. return ShadowsOptimization;
  90352. }(SceneOptimization));
  90353. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90354. /**
  90355. * Defines an optimization used to turn post-processes off
  90356. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90357. */
  90358. var PostProcessesOptimization = /** @class */ (function (_super) {
  90359. __extends(PostProcessesOptimization, _super);
  90360. function PostProcessesOptimization() {
  90361. return _super !== null && _super.apply(this, arguments) || this;
  90362. }
  90363. /**
  90364. * Gets a string describing the action executed by the current optimization
  90365. * @return description string
  90366. */
  90367. PostProcessesOptimization.prototype.getDescription = function () {
  90368. return "Turning post-processes on/off";
  90369. };
  90370. /**
  90371. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90372. * @param scene defines the current scene where to apply this optimization
  90373. * @param optimizer defines the current optimizer
  90374. * @returns true if everything that can be done was applied
  90375. */
  90376. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90377. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90378. return true;
  90379. };
  90380. ;
  90381. return PostProcessesOptimization;
  90382. }(SceneOptimization));
  90383. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90384. /**
  90385. * Defines an optimization used to turn lens flares off
  90386. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90387. */
  90388. var LensFlaresOptimization = /** @class */ (function (_super) {
  90389. __extends(LensFlaresOptimization, _super);
  90390. function LensFlaresOptimization() {
  90391. return _super !== null && _super.apply(this, arguments) || this;
  90392. }
  90393. /**
  90394. * Gets a string describing the action executed by the current optimization
  90395. * @return description string
  90396. */
  90397. LensFlaresOptimization.prototype.getDescription = function () {
  90398. return "Turning lens flares on/off";
  90399. };
  90400. /**
  90401. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90402. * @param scene defines the current scene where to apply this optimization
  90403. * @param optimizer defines the current optimizer
  90404. * @returns true if everything that can be done was applied
  90405. */
  90406. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90407. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90408. return true;
  90409. };
  90410. ;
  90411. return LensFlaresOptimization;
  90412. }(SceneOptimization));
  90413. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90414. /**
  90415. * Defines an optimization based on user defined callback.
  90416. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90417. */
  90418. var CustomOptimization = /** @class */ (function (_super) {
  90419. __extends(CustomOptimization, _super);
  90420. function CustomOptimization() {
  90421. return _super !== null && _super.apply(this, arguments) || this;
  90422. }
  90423. /**
  90424. * Gets a string describing the action executed by the current optimization
  90425. * @returns description string
  90426. */
  90427. CustomOptimization.prototype.getDescription = function () {
  90428. if (this.onGetDescription) {
  90429. return this.onGetDescription();
  90430. }
  90431. return "Running user defined callback";
  90432. };
  90433. /**
  90434. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90435. * @param scene defines the current scene where to apply this optimization
  90436. * @param optimizer defines the current optimizer
  90437. * @returns true if everything that can be done was applied
  90438. */
  90439. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90440. if (this.onApply) {
  90441. return this.onApply(scene, optimizer);
  90442. }
  90443. return true;
  90444. };
  90445. ;
  90446. return CustomOptimization;
  90447. }(SceneOptimization));
  90448. BABYLON.CustomOptimization = CustomOptimization;
  90449. /**
  90450. * Defines an optimization used to turn particles off
  90451. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90452. */
  90453. var ParticlesOptimization = /** @class */ (function (_super) {
  90454. __extends(ParticlesOptimization, _super);
  90455. function ParticlesOptimization() {
  90456. return _super !== null && _super.apply(this, arguments) || this;
  90457. }
  90458. /**
  90459. * Gets a string describing the action executed by the current optimization
  90460. * @return description string
  90461. */
  90462. ParticlesOptimization.prototype.getDescription = function () {
  90463. return "Turning particles on/off";
  90464. };
  90465. /**
  90466. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90467. * @param scene defines the current scene where to apply this optimization
  90468. * @param optimizer defines the current optimizer
  90469. * @returns true if everything that can be done was applied
  90470. */
  90471. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90472. scene.particlesEnabled = optimizer.isInImprovementMode;
  90473. return true;
  90474. };
  90475. ;
  90476. return ParticlesOptimization;
  90477. }(SceneOptimization));
  90478. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90479. /**
  90480. * Defines an optimization used to turn render targets off
  90481. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90482. */
  90483. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90484. __extends(RenderTargetsOptimization, _super);
  90485. function RenderTargetsOptimization() {
  90486. return _super !== null && _super.apply(this, arguments) || this;
  90487. }
  90488. /**
  90489. * Gets a string describing the action executed by the current optimization
  90490. * @return description string
  90491. */
  90492. RenderTargetsOptimization.prototype.getDescription = function () {
  90493. return "Turning render targets off";
  90494. };
  90495. /**
  90496. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90497. * @param scene defines the current scene where to apply this optimization
  90498. * @param optimizer defines the current optimizer
  90499. * @returns true if everything that can be done was applied
  90500. */
  90501. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90502. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90503. return true;
  90504. };
  90505. ;
  90506. return RenderTargetsOptimization;
  90507. }(SceneOptimization));
  90508. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90509. /**
  90510. * Defines an optimization used to merge meshes with compatible materials
  90511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90512. */
  90513. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90514. __extends(MergeMeshesOptimization, _super);
  90515. function MergeMeshesOptimization() {
  90516. var _this = _super !== null && _super.apply(this, arguments) || this;
  90517. _this._canBeMerged = function (abstractMesh) {
  90518. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90519. return false;
  90520. }
  90521. var mesh = abstractMesh;
  90522. if (!mesh.isVisible || !mesh.isEnabled()) {
  90523. return false;
  90524. }
  90525. if (mesh.instances.length > 0) {
  90526. return false;
  90527. }
  90528. if (mesh.skeleton || mesh.hasLODLevels) {
  90529. return false;
  90530. }
  90531. if (mesh.parent) {
  90532. return false;
  90533. }
  90534. return true;
  90535. };
  90536. return _this;
  90537. }
  90538. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90539. /**
  90540. * Gets or sets a boolean which defines if optimization octree has to be updated
  90541. */
  90542. get: function () {
  90543. return MergeMeshesOptimization._UpdateSelectionTree;
  90544. },
  90545. /**
  90546. * Gets or sets a boolean which defines if optimization octree has to be updated
  90547. */
  90548. set: function (value) {
  90549. MergeMeshesOptimization._UpdateSelectionTree = value;
  90550. },
  90551. enumerable: true,
  90552. configurable: true
  90553. });
  90554. /**
  90555. * Gets a string describing the action executed by the current optimization
  90556. * @return description string
  90557. */
  90558. MergeMeshesOptimization.prototype.getDescription = function () {
  90559. return "Merging similar meshes together";
  90560. };
  90561. /**
  90562. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90563. * @param scene defines the current scene where to apply this optimization
  90564. * @param optimizer defines the current optimizer
  90565. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90566. * @returns true if everything that can be done was applied
  90567. */
  90568. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90569. var globalPool = scene.meshes.slice(0);
  90570. var globalLength = globalPool.length;
  90571. for (var index = 0; index < globalLength; index++) {
  90572. var currentPool = new Array();
  90573. var current = globalPool[index];
  90574. // Checks
  90575. if (!this._canBeMerged(current)) {
  90576. continue;
  90577. }
  90578. currentPool.push(current);
  90579. // Find compatible meshes
  90580. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90581. var otherMesh = globalPool[subIndex];
  90582. if (!this._canBeMerged(otherMesh)) {
  90583. continue;
  90584. }
  90585. if (otherMesh.material !== current.material) {
  90586. continue;
  90587. }
  90588. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90589. continue;
  90590. }
  90591. currentPool.push(otherMesh);
  90592. globalLength--;
  90593. globalPool.splice(subIndex, 1);
  90594. subIndex--;
  90595. }
  90596. if (currentPool.length < 2) {
  90597. continue;
  90598. }
  90599. // Merge meshes
  90600. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90601. }
  90602. if (updateSelectionTree != undefined) {
  90603. if (updateSelectionTree) {
  90604. scene.createOrUpdateSelectionOctree();
  90605. }
  90606. }
  90607. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90608. scene.createOrUpdateSelectionOctree();
  90609. }
  90610. return true;
  90611. };
  90612. ;
  90613. MergeMeshesOptimization._UpdateSelectionTree = false;
  90614. return MergeMeshesOptimization;
  90615. }(SceneOptimization));
  90616. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90617. /**
  90618. * Defines a list of options used by SceneOptimizer
  90619. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90620. */
  90621. var SceneOptimizerOptions = /** @class */ (function () {
  90622. /**
  90623. * Creates a new list of options used by SceneOptimizer
  90624. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90625. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90626. */
  90627. function SceneOptimizerOptions(
  90628. /**
  90629. * Defines the target frame rate to reach (60 by default)
  90630. */
  90631. targetFrameRate,
  90632. /**
  90633. * Defines the interval between two checkes (2000ms by default)
  90634. */
  90635. trackerDuration) {
  90636. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90637. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90638. this.targetFrameRate = targetFrameRate;
  90639. this.trackerDuration = trackerDuration;
  90640. /**
  90641. * Gets the list of optimizations to apply
  90642. */
  90643. this.optimizations = new Array();
  90644. }
  90645. /**
  90646. * Add a new optimization
  90647. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90648. * @returns the current SceneOptimizerOptions
  90649. */
  90650. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90651. this.optimizations.push(optimization);
  90652. return this;
  90653. };
  90654. /**
  90655. * Add a new custom optimization
  90656. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90657. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90658. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90659. * @returns the current SceneOptimizerOptions
  90660. */
  90661. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90662. if (priority === void 0) { priority = 0; }
  90663. var optimization = new CustomOptimization(priority);
  90664. optimization.onApply = onApply;
  90665. optimization.onGetDescription = onGetDescription;
  90666. this.optimizations.push(optimization);
  90667. return this;
  90668. };
  90669. /**
  90670. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90671. * @param targetFrameRate defines the target frame rate (60 by default)
  90672. * @returns a SceneOptimizerOptions object
  90673. */
  90674. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90675. var result = new SceneOptimizerOptions(targetFrameRate);
  90676. var priority = 0;
  90677. result.addOptimization(new MergeMeshesOptimization(priority));
  90678. result.addOptimization(new ShadowsOptimization(priority));
  90679. result.addOptimization(new LensFlaresOptimization(priority));
  90680. // Next priority
  90681. priority++;
  90682. result.addOptimization(new PostProcessesOptimization(priority));
  90683. result.addOptimization(new ParticlesOptimization(priority));
  90684. // Next priority
  90685. priority++;
  90686. result.addOptimization(new TextureOptimization(priority, 1024));
  90687. return result;
  90688. };
  90689. /**
  90690. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90691. * @param targetFrameRate defines the target frame rate (60 by default)
  90692. * @returns a SceneOptimizerOptions object
  90693. */
  90694. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90695. var result = new SceneOptimizerOptions(targetFrameRate);
  90696. var priority = 0;
  90697. result.addOptimization(new MergeMeshesOptimization(priority));
  90698. result.addOptimization(new ShadowsOptimization(priority));
  90699. result.addOptimization(new LensFlaresOptimization(priority));
  90700. // Next priority
  90701. priority++;
  90702. result.addOptimization(new PostProcessesOptimization(priority));
  90703. result.addOptimization(new ParticlesOptimization(priority));
  90704. // Next priority
  90705. priority++;
  90706. result.addOptimization(new TextureOptimization(priority, 512));
  90707. // Next priority
  90708. priority++;
  90709. result.addOptimization(new RenderTargetsOptimization(priority));
  90710. // Next priority
  90711. priority++;
  90712. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90713. return result;
  90714. };
  90715. /**
  90716. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90717. * @param targetFrameRate defines the target frame rate (60 by default)
  90718. * @returns a SceneOptimizerOptions object
  90719. */
  90720. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90721. var result = new SceneOptimizerOptions(targetFrameRate);
  90722. var priority = 0;
  90723. result.addOptimization(new MergeMeshesOptimization(priority));
  90724. result.addOptimization(new ShadowsOptimization(priority));
  90725. result.addOptimization(new LensFlaresOptimization(priority));
  90726. // Next priority
  90727. priority++;
  90728. result.addOptimization(new PostProcessesOptimization(priority));
  90729. result.addOptimization(new ParticlesOptimization(priority));
  90730. // Next priority
  90731. priority++;
  90732. result.addOptimization(new TextureOptimization(priority, 256));
  90733. // Next priority
  90734. priority++;
  90735. result.addOptimization(new RenderTargetsOptimization(priority));
  90736. // Next priority
  90737. priority++;
  90738. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90739. return result;
  90740. };
  90741. return SceneOptimizerOptions;
  90742. }());
  90743. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90744. /**
  90745. * Class used to run optimizations in order to reach a target frame rate
  90746. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90747. */
  90748. var SceneOptimizer = /** @class */ (function () {
  90749. /**
  90750. * Creates a new SceneOptimizer
  90751. * @param scene defines the scene to work on
  90752. * @param options defines the options to use with the SceneOptimizer
  90753. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90754. * @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)
  90755. */
  90756. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90757. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90758. if (improvementMode === void 0) { improvementMode = false; }
  90759. var _this = this;
  90760. this._isRunning = false;
  90761. this._currentPriorityLevel = 0;
  90762. this._targetFrameRate = 60;
  90763. this._trackerDuration = 2000;
  90764. this._currentFrameRate = 0;
  90765. this._improvementMode = false;
  90766. /**
  90767. * Defines an observable called when the optimizer reaches the target frame rate
  90768. */
  90769. this.onSuccessObservable = new BABYLON.Observable();
  90770. /**
  90771. * Defines an observable called when the optimizer enables an optimization
  90772. */
  90773. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90774. /**
  90775. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90776. */
  90777. this.onFailureObservable = new BABYLON.Observable();
  90778. if (!options) {
  90779. this._options = new SceneOptimizerOptions();
  90780. }
  90781. else {
  90782. this._options = options;
  90783. }
  90784. if (this._options.targetFrameRate) {
  90785. this._targetFrameRate = this._options.targetFrameRate;
  90786. }
  90787. if (this._options.trackerDuration) {
  90788. this._trackerDuration = this._options.trackerDuration;
  90789. }
  90790. if (autoGeneratePriorities) {
  90791. var priority = 0;
  90792. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90793. var optim = _a[_i];
  90794. optim.priority = priority++;
  90795. }
  90796. }
  90797. this._improvementMode = improvementMode;
  90798. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90799. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90800. _this._sceneDisposeObserver = null;
  90801. _this.dispose();
  90802. });
  90803. }
  90804. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90805. /**
  90806. * Gets a boolean indicating if the optimizer is in improvement mode
  90807. */
  90808. get: function () {
  90809. return this._improvementMode;
  90810. },
  90811. enumerable: true,
  90812. configurable: true
  90813. });
  90814. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90815. /**
  90816. * Gets the current priority level (0 at start)
  90817. */
  90818. get: function () {
  90819. return this._currentPriorityLevel;
  90820. },
  90821. enumerable: true,
  90822. configurable: true
  90823. });
  90824. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90825. /**
  90826. * Gets the current frame rate checked by the SceneOptimizer
  90827. */
  90828. get: function () {
  90829. return this._currentFrameRate;
  90830. },
  90831. enumerable: true,
  90832. configurable: true
  90833. });
  90834. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90835. /**
  90836. * Gets or sets the current target frame rate (60 by default)
  90837. */
  90838. get: function () {
  90839. return this._targetFrameRate;
  90840. },
  90841. /**
  90842. * Gets or sets the current target frame rate (60 by default)
  90843. */
  90844. set: function (value) {
  90845. this._targetFrameRate = value;
  90846. },
  90847. enumerable: true,
  90848. configurable: true
  90849. });
  90850. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90851. /**
  90852. * Gets or sets the current interval between two checks (every 2000ms by default)
  90853. */
  90854. get: function () {
  90855. return this._trackerDuration;
  90856. },
  90857. /**
  90858. * Gets or sets the current interval between two checks (every 2000ms by default)
  90859. */
  90860. set: function (value) {
  90861. this._trackerDuration = value;
  90862. },
  90863. enumerable: true,
  90864. configurable: true
  90865. });
  90866. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90867. /**
  90868. * Gets the list of active optimizations
  90869. */
  90870. get: function () {
  90871. return this._options.optimizations;
  90872. },
  90873. enumerable: true,
  90874. configurable: true
  90875. });
  90876. /**
  90877. * Stops the current optimizer
  90878. */
  90879. SceneOptimizer.prototype.stop = function () {
  90880. this._isRunning = false;
  90881. };
  90882. /**
  90883. * Reset the optimizer to initial step (current priority level = 0)
  90884. */
  90885. SceneOptimizer.prototype.reset = function () {
  90886. this._currentPriorityLevel = 0;
  90887. };
  90888. /**
  90889. * Start the optimizer. By default it will try to reach a specific framerate
  90890. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90891. */
  90892. SceneOptimizer.prototype.start = function () {
  90893. var _this = this;
  90894. if (this._isRunning) {
  90895. return;
  90896. }
  90897. this._isRunning = true;
  90898. // Let's wait for the scene to be ready before running our check
  90899. this._scene.executeWhenReady(function () {
  90900. setTimeout(function () {
  90901. _this._checkCurrentState();
  90902. }, _this._trackerDuration);
  90903. });
  90904. };
  90905. SceneOptimizer.prototype._checkCurrentState = function () {
  90906. var _this = this;
  90907. if (!this._isRunning) {
  90908. return;
  90909. }
  90910. var scene = this._scene;
  90911. var options = this._options;
  90912. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90913. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90914. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90915. this._isRunning = false;
  90916. this.onSuccessObservable.notifyObservers(this);
  90917. return;
  90918. }
  90919. // Apply current level of optimizations
  90920. var allDone = true;
  90921. var noOptimizationApplied = true;
  90922. for (var index = 0; index < options.optimizations.length; index++) {
  90923. var optimization = options.optimizations[index];
  90924. if (optimization.priority === this._currentPriorityLevel) {
  90925. noOptimizationApplied = false;
  90926. allDone = allDone && optimization.apply(scene, this);
  90927. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90928. }
  90929. }
  90930. // If no optimization was applied, this is a failure :(
  90931. if (noOptimizationApplied) {
  90932. this._isRunning = false;
  90933. this.onFailureObservable.notifyObservers(this);
  90934. return;
  90935. }
  90936. // If all optimizations were done, move to next level
  90937. if (allDone) {
  90938. this._currentPriorityLevel++;
  90939. }
  90940. // Let's the system running for a specific amount of time before checking FPS
  90941. scene.executeWhenReady(function () {
  90942. setTimeout(function () {
  90943. _this._checkCurrentState();
  90944. }, _this._trackerDuration);
  90945. });
  90946. };
  90947. /**
  90948. * Release all resources
  90949. */
  90950. SceneOptimizer.prototype.dispose = function () {
  90951. this.stop();
  90952. this.onSuccessObservable.clear();
  90953. this.onFailureObservable.clear();
  90954. this.onNewOptimizationAppliedObservable.clear();
  90955. if (this._sceneDisposeObserver) {
  90956. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90957. }
  90958. };
  90959. /**
  90960. * Helper function to create a SceneOptimizer with one single line of code
  90961. * @param scene defines the scene to work on
  90962. * @param options defines the options to use with the SceneOptimizer
  90963. * @param onSuccess defines a callback to call on success
  90964. * @param onFailure defines a callback to call on failure
  90965. * @returns the new SceneOptimizer object
  90966. */
  90967. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90968. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90969. if (onSuccess) {
  90970. optimizer.onSuccessObservable.add(function () {
  90971. onSuccess();
  90972. });
  90973. }
  90974. if (onFailure) {
  90975. optimizer.onFailureObservable.add(function () {
  90976. onFailure();
  90977. });
  90978. }
  90979. optimizer.start();
  90980. return optimizer;
  90981. };
  90982. return SceneOptimizer;
  90983. }());
  90984. BABYLON.SceneOptimizer = SceneOptimizer;
  90985. })(BABYLON || (BABYLON = {}));
  90986. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90987. var BABYLON;
  90988. (function (BABYLON) {
  90989. var OutlineRenderer = /** @class */ (function () {
  90990. function OutlineRenderer(scene) {
  90991. this.zOffset = 1;
  90992. this._scene = scene;
  90993. }
  90994. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90995. var _this = this;
  90996. if (useOverlay === void 0) { useOverlay = false; }
  90997. var scene = this._scene;
  90998. var engine = this._scene.getEngine();
  90999. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91000. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  91001. return;
  91002. }
  91003. var mesh = subMesh.getRenderingMesh();
  91004. var material = subMesh.getMaterial();
  91005. if (!material || !scene.activeCamera) {
  91006. return;
  91007. }
  91008. engine.enableEffect(this._effect);
  91009. // Logarithmic depth
  91010. if (material.useLogarithmicDepth) {
  91011. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  91012. }
  91013. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  91014. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  91015. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  91016. // Bones
  91017. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91018. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91019. }
  91020. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  91021. // Alpha test
  91022. if (material && material.needAlphaTesting()) {
  91023. var alphaTexture = material.getAlphaTestTexture();
  91024. if (alphaTexture) {
  91025. this._effect.setTexture("diffuseSampler", alphaTexture);
  91026. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91027. }
  91028. }
  91029. engine.setZOffset(-this.zOffset);
  91030. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91031. engine.setZOffset(0);
  91032. };
  91033. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91034. var defines = [];
  91035. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91036. var mesh = subMesh.getMesh();
  91037. var material = subMesh.getMaterial();
  91038. if (material) {
  91039. // Alpha test
  91040. if (material.needAlphaTesting()) {
  91041. defines.push("#define ALPHATEST");
  91042. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91043. attribs.push(BABYLON.VertexBuffer.UVKind);
  91044. defines.push("#define UV1");
  91045. }
  91046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91047. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91048. defines.push("#define UV2");
  91049. }
  91050. }
  91051. //Logarithmic depth
  91052. if (material.useLogarithmicDepth) {
  91053. defines.push("#define LOGARITHMICDEPTH");
  91054. }
  91055. }
  91056. // Bones
  91057. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91058. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91059. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91060. if (mesh.numBoneInfluencers > 4) {
  91061. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91062. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91063. }
  91064. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91065. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91066. }
  91067. else {
  91068. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91069. }
  91070. // Instances
  91071. if (useInstances) {
  91072. defines.push("#define INSTANCES");
  91073. attribs.push("world0");
  91074. attribs.push("world1");
  91075. attribs.push("world2");
  91076. attribs.push("world3");
  91077. }
  91078. // Get correct effect
  91079. var join = defines.join("\n");
  91080. if (this._cachedDefines !== join) {
  91081. this._cachedDefines = join;
  91082. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91083. }
  91084. return this._effect.isReady();
  91085. };
  91086. return OutlineRenderer;
  91087. }());
  91088. BABYLON.OutlineRenderer = OutlineRenderer;
  91089. })(BABYLON || (BABYLON = {}));
  91090. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91091. var BABYLON;
  91092. (function (BABYLON) {
  91093. var FaceAdjacencies = /** @class */ (function () {
  91094. function FaceAdjacencies() {
  91095. this.edges = new Array();
  91096. this.edgesConnectedCount = 0;
  91097. }
  91098. return FaceAdjacencies;
  91099. }());
  91100. var EdgesRenderer = /** @class */ (function () {
  91101. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91102. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91103. if (epsilon === void 0) { epsilon = 0.95; }
  91104. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91105. this.edgesWidthScalerForOrthographic = 1000.0;
  91106. this.edgesWidthScalerForPerspective = 50.0;
  91107. this._linesPositions = new Array();
  91108. this._linesNormals = new Array();
  91109. this._linesIndices = new Array();
  91110. this._buffers = {};
  91111. this._checkVerticesInsteadOfIndices = false;
  91112. this._source = source;
  91113. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91114. this._epsilon = epsilon;
  91115. this._prepareRessources();
  91116. this._generateEdgesLines();
  91117. }
  91118. EdgesRenderer.prototype._prepareRessources = function () {
  91119. if (this._lineShader) {
  91120. return;
  91121. }
  91122. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91123. attributes: ["position", "normal"],
  91124. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91125. });
  91126. this._lineShader.disableDepthWrite = true;
  91127. this._lineShader.backFaceCulling = false;
  91128. };
  91129. EdgesRenderer.prototype._rebuild = function () {
  91130. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91131. if (buffer) {
  91132. buffer._rebuild();
  91133. }
  91134. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91135. if (buffer) {
  91136. buffer._rebuild();
  91137. }
  91138. var scene = this._source.getScene();
  91139. var engine = scene.getEngine();
  91140. this._ib = engine.createIndexBuffer(this._linesIndices);
  91141. };
  91142. EdgesRenderer.prototype.dispose = function () {
  91143. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91144. if (buffer) {
  91145. buffer.dispose();
  91146. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91147. }
  91148. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91149. if (buffer) {
  91150. buffer.dispose();
  91151. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91152. }
  91153. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91154. this._lineShader.dispose();
  91155. };
  91156. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91157. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91158. return 0;
  91159. }
  91160. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91161. return 1;
  91162. }
  91163. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91164. return 2;
  91165. }
  91166. return -1;
  91167. };
  91168. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91169. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91170. return 0;
  91171. }
  91172. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91173. return 1;
  91174. }
  91175. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91176. return 2;
  91177. }
  91178. return -1;
  91179. };
  91180. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91181. var needToCreateLine;
  91182. if (edge === undefined) {
  91183. needToCreateLine = true;
  91184. }
  91185. else {
  91186. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91187. needToCreateLine = dotProduct < this._epsilon;
  91188. }
  91189. if (needToCreateLine) {
  91190. var offset = this._linesPositions.length / 3;
  91191. var normal = p0.subtract(p1);
  91192. normal.normalize();
  91193. // Positions
  91194. this._linesPositions.push(p0.x);
  91195. this._linesPositions.push(p0.y);
  91196. this._linesPositions.push(p0.z);
  91197. this._linesPositions.push(p0.x);
  91198. this._linesPositions.push(p0.y);
  91199. this._linesPositions.push(p0.z);
  91200. this._linesPositions.push(p1.x);
  91201. this._linesPositions.push(p1.y);
  91202. this._linesPositions.push(p1.z);
  91203. this._linesPositions.push(p1.x);
  91204. this._linesPositions.push(p1.y);
  91205. this._linesPositions.push(p1.z);
  91206. // Normals
  91207. this._linesNormals.push(p1.x);
  91208. this._linesNormals.push(p1.y);
  91209. this._linesNormals.push(p1.z);
  91210. this._linesNormals.push(-1);
  91211. this._linesNormals.push(p1.x);
  91212. this._linesNormals.push(p1.y);
  91213. this._linesNormals.push(p1.z);
  91214. this._linesNormals.push(1);
  91215. this._linesNormals.push(p0.x);
  91216. this._linesNormals.push(p0.y);
  91217. this._linesNormals.push(p0.z);
  91218. this._linesNormals.push(-1);
  91219. this._linesNormals.push(p0.x);
  91220. this._linesNormals.push(p0.y);
  91221. this._linesNormals.push(p0.z);
  91222. this._linesNormals.push(1);
  91223. // Indices
  91224. this._linesIndices.push(offset);
  91225. this._linesIndices.push(offset + 1);
  91226. this._linesIndices.push(offset + 2);
  91227. this._linesIndices.push(offset);
  91228. this._linesIndices.push(offset + 2);
  91229. this._linesIndices.push(offset + 3);
  91230. }
  91231. };
  91232. EdgesRenderer.prototype._generateEdgesLines = function () {
  91233. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91234. var indices = this._source.getIndices();
  91235. if (!indices || !positions) {
  91236. return;
  91237. }
  91238. // First let's find adjacencies
  91239. var adjacencies = new Array();
  91240. var faceNormals = new Array();
  91241. var index;
  91242. var faceAdjacencies;
  91243. // Prepare faces
  91244. for (index = 0; index < indices.length; index += 3) {
  91245. faceAdjacencies = new FaceAdjacencies();
  91246. var p0Index = indices[index];
  91247. var p1Index = indices[index + 1];
  91248. var p2Index = indices[index + 2];
  91249. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91250. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91251. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91252. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91253. faceNormal.normalize();
  91254. faceNormals.push(faceNormal);
  91255. adjacencies.push(faceAdjacencies);
  91256. }
  91257. // Scan
  91258. for (index = 0; index < adjacencies.length; index++) {
  91259. faceAdjacencies = adjacencies[index];
  91260. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91261. var otherFaceAdjacencies = adjacencies[otherIndex];
  91262. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91263. break;
  91264. }
  91265. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91266. continue;
  91267. }
  91268. var otherP0 = indices[otherIndex * 3];
  91269. var otherP1 = indices[otherIndex * 3 + 1];
  91270. var otherP2 = indices[otherIndex * 3 + 2];
  91271. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91272. var otherEdgeIndex = 0;
  91273. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91274. continue;
  91275. }
  91276. switch (edgeIndex) {
  91277. case 0:
  91278. if (this._checkVerticesInsteadOfIndices) {
  91279. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91280. }
  91281. else {
  91282. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91283. }
  91284. break;
  91285. case 1:
  91286. if (this._checkVerticesInsteadOfIndices) {
  91287. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91288. }
  91289. else {
  91290. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91291. }
  91292. break;
  91293. case 2:
  91294. if (this._checkVerticesInsteadOfIndices) {
  91295. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91296. }
  91297. else {
  91298. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91299. }
  91300. break;
  91301. }
  91302. if (otherEdgeIndex === -1) {
  91303. continue;
  91304. }
  91305. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91306. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91307. faceAdjacencies.edgesConnectedCount++;
  91308. otherFaceAdjacencies.edgesConnectedCount++;
  91309. if (faceAdjacencies.edgesConnectedCount === 3) {
  91310. break;
  91311. }
  91312. }
  91313. }
  91314. }
  91315. // Create lines
  91316. for (index = 0; index < adjacencies.length; index++) {
  91317. // 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
  91318. var current = adjacencies[index];
  91319. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91320. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91321. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91322. }
  91323. // Merge into a single mesh
  91324. var engine = this._source.getScene().getEngine();
  91325. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91326. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91327. this._ib = engine.createIndexBuffer(this._linesIndices);
  91328. this._indicesCount = this._linesIndices.length;
  91329. };
  91330. EdgesRenderer.prototype.render = function () {
  91331. var scene = this._source.getScene();
  91332. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91333. return;
  91334. }
  91335. var engine = scene.getEngine();
  91336. this._lineShader._preBind();
  91337. // VBOs
  91338. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91339. scene.resetCachedMaterial();
  91340. this._lineShader.setColor4("color", this._source.edgesColor);
  91341. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91342. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91343. }
  91344. else {
  91345. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91346. }
  91347. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91348. this._lineShader.bind(this._source.getWorldMatrix());
  91349. // Draw order
  91350. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91351. this._lineShader.unbind();
  91352. engine.setDepthWrite(true);
  91353. };
  91354. return EdgesRenderer;
  91355. }());
  91356. BABYLON.EdgesRenderer = EdgesRenderer;
  91357. })(BABYLON || (BABYLON = {}));
  91358. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91359. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91360. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91361. s = arguments[i];
  91362. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91363. t[p] = s[p];
  91364. }
  91365. return t;
  91366. };
  91367. var BABYLON;
  91368. (function (BABYLON) {
  91369. /**
  91370. * The effect layer Helps adding post process effect blended with the main pass.
  91371. *
  91372. * This can be for instance use to generate glow or higlight effects on the scene.
  91373. *
  91374. * The effect layer class can not be used directly and is intented to inherited from to be
  91375. * customized per effects.
  91376. */
  91377. var EffectLayer = /** @class */ (function () {
  91378. /**
  91379. * Instantiates a new effect Layer and references it in the scene.
  91380. * @param name The name of the layer
  91381. * @param scene The scene to use the layer in
  91382. */
  91383. function EffectLayer(
  91384. /** The Friendly of the effect in the scene */
  91385. name, scene) {
  91386. this._vertexBuffers = {};
  91387. this._maxSize = 0;
  91388. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91389. this._shouldRender = true;
  91390. this._postProcesses = [];
  91391. this._textures = [];
  91392. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91393. /**
  91394. * The clear color of the texture used to generate the glow map.
  91395. */
  91396. this.neutralColor = new BABYLON.Color4();
  91397. /**
  91398. * Specifies wether the highlight layer is enabled or not.
  91399. */
  91400. this.isEnabled = true;
  91401. /**
  91402. * An event triggered when the effect layer has been disposed.
  91403. */
  91404. this.onDisposeObservable = new BABYLON.Observable();
  91405. /**
  91406. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91407. */
  91408. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91409. /**
  91410. * An event triggered when the generated texture is being merged in the scene.
  91411. */
  91412. this.onBeforeComposeObservable = new BABYLON.Observable();
  91413. /**
  91414. * An event triggered when the generated texture has been merged in the scene.
  91415. */
  91416. this.onAfterComposeObservable = new BABYLON.Observable();
  91417. /**
  91418. * An event triggered when the efffect layer changes its size.
  91419. */
  91420. this.onSizeChangedObservable = new BABYLON.Observable();
  91421. this.name = name;
  91422. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91423. this._engine = scene.getEngine();
  91424. this._maxSize = this._engine.getCaps().maxTextureSize;
  91425. this._scene.effectLayers.push(this);
  91426. // Generate Buffers
  91427. this._generateIndexBuffer();
  91428. this._genrateVertexBuffer();
  91429. }
  91430. Object.defineProperty(EffectLayer.prototype, "camera", {
  91431. /**
  91432. * Gets the camera attached to the layer.
  91433. */
  91434. get: function () {
  91435. return this._effectLayerOptions.camera;
  91436. },
  91437. enumerable: true,
  91438. configurable: true
  91439. });
  91440. /**
  91441. * Initializes the effect layer with the required options.
  91442. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91443. */
  91444. EffectLayer.prototype._init = function (options) {
  91445. // Adapt options
  91446. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91447. this._setMainTextureSize();
  91448. this._createMainTexture();
  91449. this._createTextureAndPostProcesses();
  91450. this._mergeEffect = this._createMergeEffect();
  91451. };
  91452. /**
  91453. * Generates the index buffer of the full screen quad blending to the main canvas.
  91454. */
  91455. EffectLayer.prototype._generateIndexBuffer = function () {
  91456. // Indices
  91457. var indices = [];
  91458. indices.push(0);
  91459. indices.push(1);
  91460. indices.push(2);
  91461. indices.push(0);
  91462. indices.push(2);
  91463. indices.push(3);
  91464. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91465. };
  91466. /**
  91467. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91468. */
  91469. EffectLayer.prototype._genrateVertexBuffer = function () {
  91470. // VBO
  91471. var vertices = [];
  91472. vertices.push(1, 1);
  91473. vertices.push(-1, 1);
  91474. vertices.push(-1, -1);
  91475. vertices.push(1, -1);
  91476. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91477. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91478. };
  91479. /**
  91480. * Sets the main texture desired size which is the closest power of two
  91481. * of the engine canvas size.
  91482. */
  91483. EffectLayer.prototype._setMainTextureSize = function () {
  91484. if (this._effectLayerOptions.mainTextureFixedSize) {
  91485. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91486. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91487. }
  91488. else {
  91489. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91490. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91491. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91492. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91493. }
  91494. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91495. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91496. };
  91497. /**
  91498. * Creates the main texture for the effect layer.
  91499. */
  91500. EffectLayer.prototype._createMainTexture = function () {
  91501. var _this = this;
  91502. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91503. width: this._mainTextureDesiredSize.width,
  91504. height: this._mainTextureDesiredSize.height
  91505. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91506. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91507. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91508. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91509. this._mainTexture.anisotropicFilteringLevel = 1;
  91510. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91511. this._mainTexture.renderParticles = false;
  91512. this._mainTexture.renderList = null;
  91513. this._mainTexture.ignoreCameraViewport = true;
  91514. // Custom render function
  91515. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91516. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91517. var index;
  91518. var engine = _this._scene.getEngine();
  91519. if (depthOnlySubMeshes.length) {
  91520. engine.setColorWrite(false);
  91521. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91522. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91523. }
  91524. engine.setColorWrite(true);
  91525. }
  91526. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91527. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91528. }
  91529. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91530. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91531. }
  91532. for (index = 0; index < transparentSubMeshes.length; index++) {
  91533. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91534. }
  91535. };
  91536. this._mainTexture.onClearObservable.add(function (engine) {
  91537. engine.clear(_this.neutralColor, true, true, true);
  91538. });
  91539. };
  91540. /**
  91541. * Checks for the readiness of the element composing the layer.
  91542. * @param subMesh the mesh to check for
  91543. * @param useInstances specify wether or not to use instances to render the mesh
  91544. * @param emissiveTexture the associated emissive texture used to generate the glow
  91545. * @return true if ready otherwise, false
  91546. */
  91547. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91548. var material = subMesh.getMaterial();
  91549. if (!material) {
  91550. return false;
  91551. }
  91552. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91553. return false;
  91554. }
  91555. var defines = [];
  91556. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91557. var mesh = subMesh.getMesh();
  91558. var uv1 = false;
  91559. var uv2 = false;
  91560. // Alpha test
  91561. if (material && material.needAlphaTesting()) {
  91562. var alphaTexture = material.getAlphaTestTexture();
  91563. if (alphaTexture) {
  91564. defines.push("#define ALPHATEST");
  91565. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91566. alphaTexture.coordinatesIndex === 1) {
  91567. defines.push("#define DIFFUSEUV2");
  91568. uv2 = true;
  91569. }
  91570. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91571. defines.push("#define DIFFUSEUV1");
  91572. uv1 = true;
  91573. }
  91574. }
  91575. }
  91576. // Emissive
  91577. if (emissiveTexture) {
  91578. defines.push("#define EMISSIVE");
  91579. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91580. emissiveTexture.coordinatesIndex === 1) {
  91581. defines.push("#define EMISSIVEUV2");
  91582. uv2 = true;
  91583. }
  91584. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91585. defines.push("#define EMISSIVEUV1");
  91586. uv1 = true;
  91587. }
  91588. }
  91589. if (uv1) {
  91590. attribs.push(BABYLON.VertexBuffer.UVKind);
  91591. defines.push("#define UV1");
  91592. }
  91593. if (uv2) {
  91594. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91595. defines.push("#define UV2");
  91596. }
  91597. // Bones
  91598. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91601. if (mesh.numBoneInfluencers > 4) {
  91602. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91603. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91604. }
  91605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91606. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91607. }
  91608. else {
  91609. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91610. }
  91611. // Morph targets
  91612. var manager = mesh.morphTargetManager;
  91613. var morphInfluencers = 0;
  91614. if (manager) {
  91615. if (manager.numInfluencers > 0) {
  91616. defines.push("#define MORPHTARGETS");
  91617. morphInfluencers = manager.numInfluencers;
  91618. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91619. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91620. }
  91621. }
  91622. // Instances
  91623. if (useInstances) {
  91624. defines.push("#define INSTANCES");
  91625. attribs.push("world0");
  91626. attribs.push("world1");
  91627. attribs.push("world2");
  91628. attribs.push("world3");
  91629. }
  91630. // Get correct effect
  91631. var join = defines.join("\n");
  91632. if (this._cachedDefines !== join) {
  91633. this._cachedDefines = join;
  91634. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91635. }
  91636. return this._effectLayerMapGenerationEffect.isReady();
  91637. };
  91638. /**
  91639. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91640. */
  91641. EffectLayer.prototype.render = function () {
  91642. var currentEffect = this._mergeEffect;
  91643. // Check
  91644. if (!currentEffect.isReady())
  91645. return;
  91646. for (var i = 0; i < this._postProcesses.length; i++) {
  91647. if (!this._postProcesses[i].isReady()) {
  91648. return;
  91649. }
  91650. }
  91651. var engine = this._scene.getEngine();
  91652. this.onBeforeComposeObservable.notifyObservers(this);
  91653. // Render
  91654. engine.enableEffect(currentEffect);
  91655. engine.setState(false);
  91656. // VBOs
  91657. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91658. // Cache
  91659. var previousAlphaMode = engine.getAlphaMode();
  91660. // Go Blend.
  91661. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91662. // Blends the map on the main canvas.
  91663. this._internalRender(currentEffect);
  91664. // Restore Alpha
  91665. engine.setAlphaMode(previousAlphaMode);
  91666. this.onAfterComposeObservable.notifyObservers(this);
  91667. // Handle size changes.
  91668. var size = this._mainTexture.getSize();
  91669. this._setMainTextureSize();
  91670. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91671. // Recreate RTT and post processes on size change.
  91672. this.onSizeChangedObservable.notifyObservers(this);
  91673. this._disposeTextureAndPostProcesses();
  91674. this._createMainTexture();
  91675. this._createTextureAndPostProcesses();
  91676. }
  91677. };
  91678. /**
  91679. * Determine if a given mesh will be used in the current effect.
  91680. * @param mesh mesh to test
  91681. * @returns true if the mesh will be used
  91682. */
  91683. EffectLayer.prototype.hasMesh = function (mesh) {
  91684. return true;
  91685. };
  91686. /**
  91687. * Returns true if the layer contains information to display, otherwise false.
  91688. * @returns true if the glow layer should be rendered
  91689. */
  91690. EffectLayer.prototype.shouldRender = function () {
  91691. return this.isEnabled && this._shouldRender;
  91692. };
  91693. /**
  91694. * Returns true if the mesh should render, otherwise false.
  91695. * @param mesh The mesh to render
  91696. * @returns true if it should render otherwise false
  91697. */
  91698. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91699. return true;
  91700. };
  91701. /**
  91702. * Returns true if the mesh should render, otherwise false.
  91703. * @param mesh The mesh to render
  91704. * @returns true if it should render otherwise false
  91705. */
  91706. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91707. return true;
  91708. };
  91709. /**
  91710. * Renders the submesh passed in parameter to the generation map.
  91711. */
  91712. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91713. var _this = this;
  91714. if (!this.shouldRender()) {
  91715. return;
  91716. }
  91717. var material = subMesh.getMaterial();
  91718. var mesh = subMesh.getRenderingMesh();
  91719. var scene = this._scene;
  91720. var engine = scene.getEngine();
  91721. if (!material) {
  91722. return;
  91723. }
  91724. // Do not block in blend mode.
  91725. if (material.needAlphaBlendingForMesh(mesh)) {
  91726. return;
  91727. }
  91728. // Culling
  91729. engine.setState(material.backFaceCulling);
  91730. // Managing instances
  91731. var batch = mesh._getInstancesRenderList(subMesh._id);
  91732. if (batch.mustReturn) {
  91733. return;
  91734. }
  91735. // Early Exit per mesh
  91736. if (!this._shouldRenderMesh(mesh)) {
  91737. return;
  91738. }
  91739. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91740. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91741. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91742. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91743. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91744. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91745. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91746. // Alpha test
  91747. if (material && material.needAlphaTesting()) {
  91748. var alphaTexture = material.getAlphaTestTexture();
  91749. if (alphaTexture) {
  91750. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91751. var textureMatrix = alphaTexture.getTextureMatrix();
  91752. if (textureMatrix) {
  91753. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91754. }
  91755. }
  91756. }
  91757. // Glow emissive only
  91758. if (this._emissiveTextureAndColor.texture) {
  91759. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91760. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91761. }
  91762. // Bones
  91763. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91764. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91765. }
  91766. // Morph targets
  91767. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91768. // Draw
  91769. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91770. }
  91771. else {
  91772. // Need to reset refresh rate of the shadowMap
  91773. this._mainTexture.resetRefreshCounter();
  91774. }
  91775. };
  91776. /**
  91777. * Rebuild the required buffers.
  91778. * @hidden Internal use only.
  91779. */
  91780. EffectLayer.prototype._rebuild = function () {
  91781. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91782. if (vb) {
  91783. vb._rebuild();
  91784. }
  91785. this._generateIndexBuffer();
  91786. };
  91787. /**
  91788. * Dispose only the render target textures and post process.
  91789. */
  91790. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91791. this._mainTexture.dispose();
  91792. for (var i = 0; i < this._postProcesses.length; i++) {
  91793. if (this._postProcesses[i]) {
  91794. this._postProcesses[i].dispose();
  91795. }
  91796. }
  91797. this._postProcesses = [];
  91798. for (var i = 0; i < this._textures.length; i++) {
  91799. if (this._textures[i]) {
  91800. this._textures[i].dispose();
  91801. }
  91802. }
  91803. this._textures = [];
  91804. };
  91805. /**
  91806. * Dispose the highlight layer and free resources.
  91807. */
  91808. EffectLayer.prototype.dispose = function () {
  91809. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91810. if (vertexBuffer) {
  91811. vertexBuffer.dispose();
  91812. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91813. }
  91814. if (this._indexBuffer) {
  91815. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91816. this._indexBuffer = null;
  91817. }
  91818. // Clean textures and post processes
  91819. this._disposeTextureAndPostProcesses();
  91820. // Remove from scene
  91821. var index = this._scene.effectLayers.indexOf(this, 0);
  91822. if (index > -1) {
  91823. this._scene.effectLayers.splice(index, 1);
  91824. }
  91825. // Callback
  91826. this.onDisposeObservable.notifyObservers(this);
  91827. this.onDisposeObservable.clear();
  91828. this.onBeforeRenderMainTextureObservable.clear();
  91829. this.onBeforeComposeObservable.clear();
  91830. this.onAfterComposeObservable.clear();
  91831. this.onSizeChangedObservable.clear();
  91832. };
  91833. /**
  91834. * Gets the class name of the effect layer
  91835. * @returns the string with the class name of the effect layer
  91836. */
  91837. EffectLayer.prototype.getClassName = function () {
  91838. return "EffectLayer";
  91839. };
  91840. /**
  91841. * Creates an effect layer from parsed effect layer data
  91842. * @param parsedEffectLayer defines effect layer data
  91843. * @param scene defines the current scene
  91844. * @param rootUrl defines the root URL containing the effect layer information
  91845. * @returns a parsed effect Layer
  91846. */
  91847. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91848. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91849. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91850. };
  91851. __decorate([
  91852. BABYLON.serialize()
  91853. ], EffectLayer.prototype, "name", void 0);
  91854. __decorate([
  91855. BABYLON.serializeAsColor4()
  91856. ], EffectLayer.prototype, "neutralColor", void 0);
  91857. __decorate([
  91858. BABYLON.serialize()
  91859. ], EffectLayer.prototype, "isEnabled", void 0);
  91860. __decorate([
  91861. BABYLON.serializeAsCameraReference()
  91862. ], EffectLayer.prototype, "camera", null);
  91863. return EffectLayer;
  91864. }());
  91865. BABYLON.EffectLayer = EffectLayer;
  91866. })(BABYLON || (BABYLON = {}));
  91867. //# sourceMappingURL=babylon.effectLayer.js.map
  91868. var BABYLON;
  91869. (function (BABYLON) {
  91870. /**
  91871. * Special Glow Blur post process only blurring the alpha channel
  91872. * It enforces keeping the most luminous color in the color channel.
  91873. */
  91874. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91875. __extends(GlowBlurPostProcess, _super);
  91876. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91877. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91878. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91879. _this.direction = direction;
  91880. _this.kernel = kernel;
  91881. _this.onApplyObservable.add(function (effect) {
  91882. effect.setFloat2("screenSize", _this.width, _this.height);
  91883. effect.setVector2("direction", _this.direction);
  91884. effect.setFloat("blurWidth", _this.kernel);
  91885. });
  91886. return _this;
  91887. }
  91888. return GlowBlurPostProcess;
  91889. }(BABYLON.PostProcess));
  91890. /**
  91891. * The highlight layer Helps adding a glow effect around a mesh.
  91892. *
  91893. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91894. * glowy meshes to your scene.
  91895. *
  91896. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91897. */
  91898. var HighlightLayer = /** @class */ (function (_super) {
  91899. __extends(HighlightLayer, _super);
  91900. /**
  91901. * Instantiates a new highlight Layer and references it to the scene..
  91902. * @param name The name of the layer
  91903. * @param scene The scene to use the layer in
  91904. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91905. */
  91906. function HighlightLayer(name, scene, options) {
  91907. var _this = _super.call(this, name, scene) || this;
  91908. _this.name = name;
  91909. /**
  91910. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91911. */
  91912. _this.innerGlow = true;
  91913. /**
  91914. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91915. */
  91916. _this.outerGlow = true;
  91917. /**
  91918. * An event triggered when the highlight layer is being blurred.
  91919. */
  91920. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91921. /**
  91922. * An event triggered when the highlight layer has been blurred.
  91923. */
  91924. _this.onAfterBlurObservable = new BABYLON.Observable();
  91925. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91926. _this._meshes = {};
  91927. _this._excludedMeshes = {};
  91928. _this.neutralColor = HighlightLayer.NeutralColor;
  91929. // Warn on stencil
  91930. if (!_this._engine.isStencilEnable) {
  91931. 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 }");
  91932. }
  91933. // Adapt options
  91934. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91935. // Initialize the layer
  91936. _this._init({
  91937. alphaBlendingMode: _this._options.alphaBlendingMode,
  91938. camera: _this._options.camera,
  91939. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91940. mainTextureRatio: _this._options.mainTextureRatio
  91941. });
  91942. // Do not render as long as no meshes have been added
  91943. _this._shouldRender = false;
  91944. return _this;
  91945. }
  91946. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91947. /**
  91948. * Gets the horizontal size of the blur.
  91949. */
  91950. get: function () {
  91951. return this._horizontalBlurPostprocess.kernel;
  91952. },
  91953. /**
  91954. * Specifies the horizontal size of the blur.
  91955. */
  91956. set: function (value) {
  91957. this._horizontalBlurPostprocess.kernel = value;
  91958. },
  91959. enumerable: true,
  91960. configurable: true
  91961. });
  91962. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91963. /**
  91964. * Gets the vertical size of the blur.
  91965. */
  91966. get: function () {
  91967. return this._verticalBlurPostprocess.kernel;
  91968. },
  91969. /**
  91970. * Specifies the vertical size of the blur.
  91971. */
  91972. set: function (value) {
  91973. this._verticalBlurPostprocess.kernel = value;
  91974. },
  91975. enumerable: true,
  91976. configurable: true
  91977. });
  91978. /**
  91979. * Get the effect name of the layer.
  91980. * @return The effect name
  91981. */
  91982. HighlightLayer.prototype.getEffectName = function () {
  91983. return HighlightLayer.EffectName;
  91984. };
  91985. /**
  91986. * Create the merge effect. This is the shader use to blit the information back
  91987. * to the main canvas at the end of the scene rendering.
  91988. */
  91989. HighlightLayer.prototype._createMergeEffect = function () {
  91990. // Effect
  91991. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91992. };
  91993. /**
  91994. * Creates the render target textures and post processes used in the highlight layer.
  91995. */
  91996. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91997. var _this = this;
  91998. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91999. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  92000. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92001. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92002. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  92003. width: blurTextureWidth,
  92004. height: blurTextureHeight
  92005. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92006. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92007. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92008. this._blurTexture.anisotropicFilteringLevel = 16;
  92009. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  92010. this._blurTexture.renderParticles = false;
  92011. this._blurTexture.ignoreCameraViewport = true;
  92012. this._textures = [this._blurTexture];
  92013. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  92014. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92015. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  92016. effect.setTexture("textureSampler", _this._mainTexture);
  92017. });
  92018. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92019. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92020. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92021. });
  92022. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  92023. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92024. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92025. });
  92026. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92027. }
  92028. else {
  92029. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92030. width: blurTextureWidth,
  92031. height: blurTextureHeight
  92032. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92033. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92034. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92035. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92036. effect.setTexture("textureSampler", _this._mainTexture);
  92037. });
  92038. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92039. width: blurTextureWidth,
  92040. height: blurTextureHeight
  92041. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92042. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92043. }
  92044. this._mainTexture.onAfterUnbindObservable.add(function () {
  92045. _this.onBeforeBlurObservable.notifyObservers(_this);
  92046. var internalTexture = _this._blurTexture.getInternalTexture();
  92047. if (internalTexture) {
  92048. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92049. }
  92050. _this.onAfterBlurObservable.notifyObservers(_this);
  92051. });
  92052. // Prevent autoClear.
  92053. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92054. };
  92055. /**
  92056. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92057. */
  92058. HighlightLayer.prototype.needStencil = function () {
  92059. return true;
  92060. };
  92061. /**
  92062. * Checks for the readiness of the element composing the layer.
  92063. * @param subMesh the mesh to check for
  92064. * @param useInstances specify wether or not to use instances to render the mesh
  92065. * @param emissiveTexture the associated emissive texture used to generate the glow
  92066. * @return true if ready otherwise, false
  92067. */
  92068. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92069. var material = subMesh.getMaterial();
  92070. var mesh = subMesh.getRenderingMesh();
  92071. if (!material || !mesh || !this._meshes) {
  92072. return false;
  92073. }
  92074. var emissiveTexture = null;
  92075. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92076. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92077. emissiveTexture = material.emissiveTexture;
  92078. }
  92079. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92080. };
  92081. /**
  92082. * Implementation specific of rendering the generating effect on the main canvas.
  92083. * @param effect The effect used to render through
  92084. */
  92085. HighlightLayer.prototype._internalRender = function (effect) {
  92086. // Texture
  92087. effect.setTexture("textureSampler", this._blurTexture);
  92088. // Cache
  92089. var engine = this._engine;
  92090. var previousStencilBuffer = engine.getStencilBuffer();
  92091. var previousStencilFunction = engine.getStencilFunction();
  92092. var previousStencilMask = engine.getStencilMask();
  92093. var previousStencilOperationPass = engine.getStencilOperationPass();
  92094. var previousStencilOperationFail = engine.getStencilOperationFail();
  92095. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92096. var previousStencilReference = engine.getStencilFunctionReference();
  92097. // Stencil operations
  92098. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92099. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92100. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92101. // Draw order
  92102. engine.setStencilMask(0x00);
  92103. engine.setStencilBuffer(true);
  92104. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92105. // 2 passes inner outer
  92106. if (this.outerGlow) {
  92107. effect.setFloat("offset", 0);
  92108. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92109. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92110. }
  92111. if (this.innerGlow) {
  92112. effect.setFloat("offset", 1);
  92113. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92114. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92115. }
  92116. // Restore Cache
  92117. engine.setStencilFunction(previousStencilFunction);
  92118. engine.setStencilMask(previousStencilMask);
  92119. engine.setStencilBuffer(previousStencilBuffer);
  92120. engine.setStencilOperationPass(previousStencilOperationPass);
  92121. engine.setStencilOperationFail(previousStencilOperationFail);
  92122. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92123. engine.setStencilFunctionReference(previousStencilReference);
  92124. };
  92125. /**
  92126. * Returns true if the layer contains information to display, otherwise false.
  92127. */
  92128. HighlightLayer.prototype.shouldRender = function () {
  92129. if (_super.prototype.shouldRender.call(this)) {
  92130. return this._meshes ? true : false;
  92131. }
  92132. return false;
  92133. };
  92134. /**
  92135. * Returns true if the mesh should render, otherwise false.
  92136. * @param mesh The mesh to render
  92137. * @returns true if it should render otherwise false
  92138. */
  92139. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92140. // Excluded Mesh
  92141. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92142. return false;
  92143. }
  92144. ;
  92145. return true;
  92146. };
  92147. /**
  92148. * Sets the required values for both the emissive texture and and the main color.
  92149. */
  92150. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92151. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92152. if (highlightLayerMesh) {
  92153. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92154. }
  92155. else {
  92156. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92157. }
  92158. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92159. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92160. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92161. }
  92162. else {
  92163. this._emissiveTextureAndColor.texture = null;
  92164. }
  92165. };
  92166. /**
  92167. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92168. * @param mesh The mesh to exclude from the highlight layer
  92169. */
  92170. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92171. if (!this._excludedMeshes) {
  92172. return;
  92173. }
  92174. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92175. if (!meshExcluded) {
  92176. this._excludedMeshes[mesh.uniqueId] = {
  92177. mesh: mesh,
  92178. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92179. mesh.getEngine().setStencilBuffer(false);
  92180. }),
  92181. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92182. mesh.getEngine().setStencilBuffer(true);
  92183. }),
  92184. };
  92185. }
  92186. };
  92187. /**
  92188. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92189. * @param mesh The mesh to highlight
  92190. */
  92191. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92192. if (!this._excludedMeshes) {
  92193. return;
  92194. }
  92195. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92196. if (meshExcluded) {
  92197. if (meshExcluded.beforeRender) {
  92198. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92199. }
  92200. if (meshExcluded.afterRender) {
  92201. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92202. }
  92203. }
  92204. this._excludedMeshes[mesh.uniqueId] = null;
  92205. };
  92206. /**
  92207. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92208. * @param mesh mesh to test
  92209. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92210. */
  92211. HighlightLayer.prototype.hasMesh = function (mesh) {
  92212. if (!this._meshes) {
  92213. return false;
  92214. }
  92215. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92216. };
  92217. /**
  92218. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92219. * @param mesh The mesh to highlight
  92220. * @param color The color of the highlight
  92221. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92222. */
  92223. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92224. var _this = this;
  92225. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92226. if (!this._meshes) {
  92227. return;
  92228. }
  92229. var meshHighlight = this._meshes[mesh.uniqueId];
  92230. if (meshHighlight) {
  92231. meshHighlight.color = color;
  92232. }
  92233. else {
  92234. this._meshes[mesh.uniqueId] = {
  92235. mesh: mesh,
  92236. color: color,
  92237. // Lambda required for capture due to Observable this context
  92238. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92239. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92240. _this._defaultStencilReference(mesh);
  92241. }
  92242. else {
  92243. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92244. }
  92245. }),
  92246. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92247. glowEmissiveOnly: glowEmissiveOnly
  92248. };
  92249. }
  92250. this._shouldRender = true;
  92251. };
  92252. /**
  92253. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92254. * @param mesh The mesh to highlight
  92255. */
  92256. HighlightLayer.prototype.removeMesh = function (mesh) {
  92257. if (!this._meshes) {
  92258. return;
  92259. }
  92260. var meshHighlight = this._meshes[mesh.uniqueId];
  92261. if (meshHighlight) {
  92262. if (meshHighlight.observerHighlight) {
  92263. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92264. }
  92265. if (meshHighlight.observerDefault) {
  92266. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92267. }
  92268. delete this._meshes[mesh.uniqueId];
  92269. }
  92270. this._shouldRender = false;
  92271. for (var meshHighlightToCheck in this._meshes) {
  92272. if (this._meshes[meshHighlightToCheck]) {
  92273. this._shouldRender = true;
  92274. break;
  92275. }
  92276. }
  92277. };
  92278. /**
  92279. * Force the stencil to the normal expected value for none glowing parts
  92280. */
  92281. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92282. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92283. };
  92284. /**
  92285. * Free any resources and references associated to a mesh.
  92286. * Internal use
  92287. * @param mesh The mesh to free.
  92288. */
  92289. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92290. this.removeMesh(mesh);
  92291. this.removeExcludedMesh(mesh);
  92292. };
  92293. /**
  92294. * Dispose the highlight layer and free resources.
  92295. */
  92296. HighlightLayer.prototype.dispose = function () {
  92297. if (this._meshes) {
  92298. // Clean mesh references
  92299. for (var id in this._meshes) {
  92300. var meshHighlight = this._meshes[id];
  92301. if (meshHighlight && meshHighlight.mesh) {
  92302. if (meshHighlight.observerHighlight) {
  92303. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92304. }
  92305. if (meshHighlight.observerDefault) {
  92306. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92307. }
  92308. }
  92309. }
  92310. this._meshes = null;
  92311. }
  92312. if (this._excludedMeshes) {
  92313. for (var id in this._excludedMeshes) {
  92314. var meshHighlight = this._excludedMeshes[id];
  92315. if (meshHighlight) {
  92316. if (meshHighlight.beforeRender) {
  92317. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92318. }
  92319. if (meshHighlight.afterRender) {
  92320. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92321. }
  92322. }
  92323. }
  92324. this._excludedMeshes = null;
  92325. }
  92326. _super.prototype.dispose.call(this);
  92327. };
  92328. /**
  92329. * Gets the class name of the effect layer
  92330. * @returns the string with the class name of the effect layer
  92331. */
  92332. HighlightLayer.prototype.getClassName = function () {
  92333. return "HighlightLayer";
  92334. };
  92335. /**
  92336. * Serializes this Highlight layer
  92337. * @returns a serialized Highlight layer object
  92338. */
  92339. HighlightLayer.prototype.serialize = function () {
  92340. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92341. serializationObject.customType = "BABYLON.HighlightLayer";
  92342. // Highlighted meshes
  92343. serializationObject.meshes = [];
  92344. if (this._meshes) {
  92345. for (var m in this._meshes) {
  92346. var mesh = this._meshes[m];
  92347. if (mesh) {
  92348. serializationObject.meshes.push({
  92349. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92350. color: mesh.color.asArray(),
  92351. meshId: mesh.mesh.id
  92352. });
  92353. }
  92354. }
  92355. }
  92356. // Excluded meshes
  92357. serializationObject.excludedMeshes = [];
  92358. if (this._excludedMeshes) {
  92359. for (var e in this._excludedMeshes) {
  92360. var excludedMesh = this._excludedMeshes[e];
  92361. if (excludedMesh) {
  92362. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92363. }
  92364. }
  92365. }
  92366. return serializationObject;
  92367. };
  92368. /**
  92369. * Creates a Highlight layer from parsed Highlight layer data
  92370. * @param parsedHightlightLayer defines the Highlight layer data
  92371. * @param scene defines the current scene
  92372. * @param rootUrl defines the root URL containing the Highlight layer information
  92373. * @returns a parsed Highlight layer
  92374. */
  92375. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92376. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92377. var index;
  92378. // Excluded meshes
  92379. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92380. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92381. if (mesh) {
  92382. hl.addExcludedMesh(mesh);
  92383. }
  92384. }
  92385. // Included meshes
  92386. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92387. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92388. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92389. if (mesh) {
  92390. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92391. }
  92392. }
  92393. return hl;
  92394. };
  92395. /**
  92396. * Effect Name of the highlight layer.
  92397. */
  92398. HighlightLayer.EffectName = "HighlightLayer";
  92399. /**
  92400. * The neutral color used during the preparation of the glow effect.
  92401. * This is black by default as the blend operation is a blend operation.
  92402. */
  92403. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92404. /**
  92405. * Stencil value used for glowing meshes.
  92406. */
  92407. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92408. /**
  92409. * Stencil value used for the other meshes in the scene.
  92410. */
  92411. HighlightLayer.NormalMeshStencilReference = 0x01;
  92412. __decorate([
  92413. BABYLON.serialize()
  92414. ], HighlightLayer.prototype, "innerGlow", void 0);
  92415. __decorate([
  92416. BABYLON.serialize()
  92417. ], HighlightLayer.prototype, "outerGlow", void 0);
  92418. __decorate([
  92419. BABYLON.serialize()
  92420. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92421. __decorate([
  92422. BABYLON.serialize()
  92423. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92424. __decorate([
  92425. BABYLON.serialize("options")
  92426. ], HighlightLayer.prototype, "_options", void 0);
  92427. return HighlightLayer;
  92428. }(BABYLON.EffectLayer));
  92429. BABYLON.HighlightLayer = HighlightLayer;
  92430. })(BABYLON || (BABYLON = {}));
  92431. //# sourceMappingURL=babylon.highlightLayer.js.map
  92432. var BABYLON;
  92433. (function (BABYLON) {
  92434. /**
  92435. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92436. *
  92437. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92438. * glowy meshes to your scene.
  92439. *
  92440. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92441. */
  92442. var GlowLayer = /** @class */ (function (_super) {
  92443. __extends(GlowLayer, _super);
  92444. /**
  92445. * Instantiates a new glow Layer and references it to the scene.
  92446. * @param name The name of the layer
  92447. * @param scene The scene to use the layer in
  92448. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92449. */
  92450. function GlowLayer(name, scene, options) {
  92451. var _this = _super.call(this, name, scene) || this;
  92452. _this._intensity = 1.0;
  92453. _this._includedOnlyMeshes = [];
  92454. _this._excludedMeshes = [];
  92455. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92456. // Adapt options
  92457. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92458. // Initialize the layer
  92459. _this._init({
  92460. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92461. camera: _this._options.camera,
  92462. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92463. mainTextureRatio: _this._options.mainTextureRatio
  92464. });
  92465. return _this;
  92466. }
  92467. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92468. /**
  92469. * Gets the kernel size of the blur.
  92470. */
  92471. get: function () {
  92472. return this._horizontalBlurPostprocess1.kernel;
  92473. },
  92474. /**
  92475. * Sets the kernel size of the blur.
  92476. */
  92477. set: function (value) {
  92478. this._horizontalBlurPostprocess1.kernel = value;
  92479. this._verticalBlurPostprocess1.kernel = value;
  92480. this._horizontalBlurPostprocess2.kernel = value;
  92481. this._verticalBlurPostprocess2.kernel = value;
  92482. },
  92483. enumerable: true,
  92484. configurable: true
  92485. });
  92486. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92487. /**
  92488. * Gets the glow intensity.
  92489. */
  92490. get: function () {
  92491. return this._intensity;
  92492. },
  92493. /**
  92494. * Sets the glow intensity.
  92495. */
  92496. set: function (value) {
  92497. this._intensity = value;
  92498. },
  92499. enumerable: true,
  92500. configurable: true
  92501. });
  92502. /**
  92503. * Get the effect name of the layer.
  92504. * @return The effect name
  92505. */
  92506. GlowLayer.prototype.getEffectName = function () {
  92507. return GlowLayer.EffectName;
  92508. };
  92509. /**
  92510. * Create the merge effect. This is the shader use to blit the information back
  92511. * to the main canvas at the end of the scene rendering.
  92512. */
  92513. GlowLayer.prototype._createMergeEffect = function () {
  92514. // Effect
  92515. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92516. };
  92517. /**
  92518. * Creates the render target textures and post processes used in the glow layer.
  92519. */
  92520. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92521. var _this = this;
  92522. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92523. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92524. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92525. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92526. var textureType = 0;
  92527. if (this._engine.getCaps().textureHalfFloatRender) {
  92528. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92529. }
  92530. else {
  92531. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92532. }
  92533. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92534. width: blurTextureWidth,
  92535. height: blurTextureHeight
  92536. }, this._scene, false, true, textureType);
  92537. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92538. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92539. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92540. this._blurTexture1.renderParticles = false;
  92541. this._blurTexture1.ignoreCameraViewport = true;
  92542. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92543. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92544. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92545. width: blurTextureWidth2,
  92546. height: blurTextureHeight2
  92547. }, this._scene, false, true, textureType);
  92548. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92549. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92550. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92551. this._blurTexture2.renderParticles = false;
  92552. this._blurTexture2.ignoreCameraViewport = true;
  92553. this._textures = [this._blurTexture1, this._blurTexture2];
  92554. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92555. width: blurTextureWidth,
  92556. height: blurTextureHeight
  92557. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92558. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92559. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92560. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92561. effect.setTexture("textureSampler", _this._mainTexture);
  92562. });
  92563. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92564. width: blurTextureWidth,
  92565. height: blurTextureHeight
  92566. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92567. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92568. width: blurTextureWidth2,
  92569. height: blurTextureHeight2
  92570. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92571. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92572. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92573. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92574. effect.setTexture("textureSampler", _this._blurTexture1);
  92575. });
  92576. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92577. width: blurTextureWidth2,
  92578. height: blurTextureHeight2
  92579. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92580. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92581. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92582. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92583. this._mainTexture.samples = this._options.mainTextureSamples;
  92584. this._mainTexture.onAfterUnbindObservable.add(function () {
  92585. var internalTexture = _this._blurTexture1.getInternalTexture();
  92586. if (internalTexture) {
  92587. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92588. internalTexture = _this._blurTexture2.getInternalTexture();
  92589. if (internalTexture) {
  92590. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92591. }
  92592. }
  92593. });
  92594. // Prevent autoClear.
  92595. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92596. };
  92597. /**
  92598. * Checks for the readiness of the element composing the layer.
  92599. * @param subMesh the mesh to check for
  92600. * @param useInstances specify wether or not to use instances to render the mesh
  92601. * @param emissiveTexture the associated emissive texture used to generate the glow
  92602. * @return true if ready otherwise, false
  92603. */
  92604. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92605. var material = subMesh.getMaterial();
  92606. var mesh = subMesh.getRenderingMesh();
  92607. if (!material || !mesh) {
  92608. return false;
  92609. }
  92610. var emissiveTexture = material.emissiveTexture;
  92611. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92612. };
  92613. /**
  92614. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92615. */
  92616. GlowLayer.prototype.needStencil = function () {
  92617. return false;
  92618. };
  92619. /**
  92620. * Implementation specific of rendering the generating effect on the main canvas.
  92621. * @param effect The effect used to render through
  92622. */
  92623. GlowLayer.prototype._internalRender = function (effect) {
  92624. // Texture
  92625. effect.setTexture("textureSampler", this._blurTexture1);
  92626. effect.setTexture("textureSampler2", this._blurTexture2);
  92627. effect.setFloat("offset", this._intensity);
  92628. // Cache
  92629. var engine = this._engine;
  92630. var previousStencilBuffer = engine.getStencilBuffer();
  92631. // Draw order
  92632. engine.setStencilBuffer(false);
  92633. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92634. // Draw order
  92635. engine.setStencilBuffer(previousStencilBuffer);
  92636. };
  92637. /**
  92638. * Sets the required values for both the emissive texture and and the main color.
  92639. */
  92640. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92641. var textureLevel = 1.0;
  92642. if (this.customEmissiveTextureSelector) {
  92643. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92644. }
  92645. else {
  92646. if (material) {
  92647. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92648. if (this._emissiveTextureAndColor.texture) {
  92649. textureLevel = this._emissiveTextureAndColor.texture.level;
  92650. }
  92651. }
  92652. else {
  92653. this._emissiveTextureAndColor.texture = null;
  92654. }
  92655. }
  92656. if (this.customEmissiveColorSelector) {
  92657. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92658. }
  92659. else {
  92660. if (material.emissiveColor) {
  92661. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92662. }
  92663. else {
  92664. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92665. }
  92666. }
  92667. };
  92668. /**
  92669. * Returns true if the mesh should render, otherwise false.
  92670. * @param mesh The mesh to render
  92671. * @returns true if it should render otherwise false
  92672. */
  92673. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92674. return this.hasMesh(mesh);
  92675. };
  92676. /**
  92677. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92678. * @param mesh The mesh to exclude from the glow layer
  92679. */
  92680. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92681. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92682. this._excludedMeshes.push(mesh.uniqueId);
  92683. }
  92684. };
  92685. /**
  92686. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92687. * @param mesh The mesh to remove
  92688. */
  92689. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92690. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92691. if (index !== -1) {
  92692. this._excludedMeshes.splice(index, 1);
  92693. }
  92694. };
  92695. /**
  92696. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92697. * @param mesh The mesh to include in the glow layer
  92698. */
  92699. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92700. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92701. this._includedOnlyMeshes.push(mesh.uniqueId);
  92702. }
  92703. };
  92704. /**
  92705. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92706. * @param mesh The mesh to remove
  92707. */
  92708. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92709. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92710. if (index !== -1) {
  92711. this._includedOnlyMeshes.splice(index, 1);
  92712. }
  92713. };
  92714. /**
  92715. * Determine if a given mesh will be used in the glow layer
  92716. * @param mesh The mesh to test
  92717. * @returns true if the mesh will be highlighted by the current glow layer
  92718. */
  92719. GlowLayer.prototype.hasMesh = function (mesh) {
  92720. // Included Mesh
  92721. if (this._includedOnlyMeshes.length) {
  92722. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92723. }
  92724. ;
  92725. // Excluded Mesh
  92726. if (this._excludedMeshes.length) {
  92727. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92728. }
  92729. ;
  92730. return true;
  92731. };
  92732. /**
  92733. * Free any resources and references associated to a mesh.
  92734. * Internal use
  92735. * @param mesh The mesh to free.
  92736. */
  92737. GlowLayer.prototype._disposeMesh = function (mesh) {
  92738. this.removeIncludedOnlyMesh(mesh);
  92739. this.removeExcludedMesh(mesh);
  92740. };
  92741. /**
  92742. * Gets the class name of the effect layer
  92743. * @returns the string with the class name of the effect layer
  92744. */
  92745. GlowLayer.prototype.getClassName = function () {
  92746. return "GlowLayer";
  92747. };
  92748. /**
  92749. * Serializes this glow layer
  92750. * @returns a serialized glow layer object
  92751. */
  92752. GlowLayer.prototype.serialize = function () {
  92753. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92754. serializationObject.customType = "BABYLON.GlowLayer";
  92755. var index;
  92756. // Included meshes
  92757. serializationObject.includedMeshes = [];
  92758. if (this._includedOnlyMeshes.length) {
  92759. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92760. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92761. if (mesh) {
  92762. serializationObject.includedMeshes.push(mesh.id);
  92763. }
  92764. }
  92765. }
  92766. // Excluded meshes
  92767. serializationObject.excludedMeshes = [];
  92768. if (this._excludedMeshes.length) {
  92769. for (index = 0; index < this._excludedMeshes.length; index++) {
  92770. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92771. if (mesh) {
  92772. serializationObject.excludedMeshes.push(mesh.id);
  92773. }
  92774. }
  92775. }
  92776. return serializationObject;
  92777. };
  92778. /**
  92779. * Creates a Glow Layer from parsed glow layer data
  92780. * @param parsedGlowLayer defines glow layer data
  92781. * @param scene defines the current scene
  92782. * @param rootUrl defines the root URL containing the glow layer information
  92783. * @returns a parsed Glow Layer
  92784. */
  92785. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92786. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92787. var index;
  92788. // Excluded meshes
  92789. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92790. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92791. if (mesh) {
  92792. gl.addExcludedMesh(mesh);
  92793. }
  92794. }
  92795. // Included meshes
  92796. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92797. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92798. if (mesh) {
  92799. gl.addIncludedOnlyMesh(mesh);
  92800. }
  92801. }
  92802. return gl;
  92803. };
  92804. /**
  92805. * Effect Name of the layer.
  92806. */
  92807. GlowLayer.EffectName = "GlowLayer";
  92808. /**
  92809. * The default blur kernel size used for the glow.
  92810. */
  92811. GlowLayer.DefaultBlurKernelSize = 32;
  92812. /**
  92813. * The default texture size ratio used for the glow.
  92814. */
  92815. GlowLayer.DefaultTextureRatio = 0.5;
  92816. __decorate([
  92817. BABYLON.serialize()
  92818. ], GlowLayer.prototype, "blurKernelSize", null);
  92819. __decorate([
  92820. BABYLON.serialize()
  92821. ], GlowLayer.prototype, "intensity", null);
  92822. __decorate([
  92823. BABYLON.serialize("options")
  92824. ], GlowLayer.prototype, "_options", void 0);
  92825. return GlowLayer;
  92826. }(BABYLON.EffectLayer));
  92827. BABYLON.GlowLayer = GlowLayer;
  92828. })(BABYLON || (BABYLON = {}));
  92829. //# sourceMappingURL=babylon.glowLayer.js.map
  92830. var BABYLON;
  92831. (function (BABYLON) {
  92832. /**
  92833. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92834. */
  92835. var AssetTaskState;
  92836. (function (AssetTaskState) {
  92837. /**
  92838. * Initialization
  92839. */
  92840. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92841. /**
  92842. * Running
  92843. */
  92844. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92845. /**
  92846. * Done
  92847. */
  92848. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92849. /**
  92850. * Error
  92851. */
  92852. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92853. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92854. /**
  92855. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92856. */
  92857. var AbstractAssetTask = /** @class */ (function () {
  92858. /**
  92859. * Creates a new {BABYLON.AssetsManager}
  92860. * @param name defines the name of the task
  92861. */
  92862. function AbstractAssetTask(
  92863. /**
  92864. * Task name
  92865. */ name) {
  92866. this.name = name;
  92867. this._isCompleted = false;
  92868. this._taskState = AssetTaskState.INIT;
  92869. }
  92870. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92871. /**
  92872. * Get if the task is completed
  92873. */
  92874. get: function () {
  92875. return this._isCompleted;
  92876. },
  92877. enumerable: true,
  92878. configurable: true
  92879. });
  92880. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92881. /**
  92882. * Gets the current state of the task
  92883. */
  92884. get: function () {
  92885. return this._taskState;
  92886. },
  92887. enumerable: true,
  92888. configurable: true
  92889. });
  92890. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92891. /**
  92892. * Gets the current error object (if task is in error)
  92893. */
  92894. get: function () {
  92895. return this._errorObject;
  92896. },
  92897. enumerable: true,
  92898. configurable: true
  92899. });
  92900. /**
  92901. * Internal only
  92902. * @hidden
  92903. */
  92904. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92905. if (this._errorObject) {
  92906. return;
  92907. }
  92908. this._errorObject = {
  92909. message: message,
  92910. exception: exception
  92911. };
  92912. };
  92913. /**
  92914. * Execute the current task
  92915. * @param scene defines the scene where you want your assets to be loaded
  92916. * @param onSuccess is a callback called when the task is successfully executed
  92917. * @param onError is a callback called if an error occurs
  92918. */
  92919. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92920. var _this = this;
  92921. this._taskState = AssetTaskState.RUNNING;
  92922. this.runTask(scene, function () {
  92923. _this.onDoneCallback(onSuccess, onError);
  92924. }, function (msg, exception) {
  92925. _this.onErrorCallback(onError, msg, exception);
  92926. });
  92927. };
  92928. /**
  92929. * Execute the current task
  92930. * @param scene defines the scene where you want your assets to be loaded
  92931. * @param onSuccess is a callback called when the task is successfully executed
  92932. * @param onError is a callback called if an error occurs
  92933. */
  92934. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92935. throw new Error("runTask is not implemented");
  92936. };
  92937. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92938. this._taskState = AssetTaskState.ERROR;
  92939. this._errorObject = {
  92940. message: message,
  92941. exception: exception
  92942. };
  92943. if (this.onError) {
  92944. this.onError(this, message, exception);
  92945. }
  92946. onError();
  92947. };
  92948. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92949. try {
  92950. this._taskState = AssetTaskState.DONE;
  92951. this._isCompleted = true;
  92952. if (this.onSuccess) {
  92953. this.onSuccess(this);
  92954. }
  92955. onSuccess();
  92956. }
  92957. catch (e) {
  92958. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92959. }
  92960. };
  92961. return AbstractAssetTask;
  92962. }());
  92963. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92964. /**
  92965. * Class used to share progress information about assets loading
  92966. */
  92967. var AssetsProgressEvent = /** @class */ (function () {
  92968. /**
  92969. * Creates a {BABYLON.AssetsProgressEvent}
  92970. * @param remainingCount defines the number of remaining tasks to process
  92971. * @param totalCount defines the total number of tasks
  92972. * @param task defines the task that was just processed
  92973. */
  92974. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92975. this.remainingCount = remainingCount;
  92976. this.totalCount = totalCount;
  92977. this.task = task;
  92978. }
  92979. return AssetsProgressEvent;
  92980. }());
  92981. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92982. /**
  92983. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92984. */
  92985. var MeshAssetTask = /** @class */ (function (_super) {
  92986. __extends(MeshAssetTask, _super);
  92987. /**
  92988. * Creates a new {BABYLON.MeshAssetTask}
  92989. * @param name defines the name of the task
  92990. * @param meshesNames defines the list of mesh's names you want to load
  92991. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92992. * @param sceneFilename defines the filename of the scene to load from
  92993. */
  92994. function MeshAssetTask(
  92995. /**
  92996. * Defines the name of the task
  92997. */
  92998. name,
  92999. /**
  93000. * Defines the list of mesh's names you want to load
  93001. */
  93002. meshesNames,
  93003. /**
  93004. * Defines the root url to use as a base to load your meshes and associated resources
  93005. */
  93006. rootUrl,
  93007. /**
  93008. * Defines the filename of the scene to load from
  93009. */
  93010. sceneFilename) {
  93011. var _this = _super.call(this, name) || this;
  93012. _this.name = name;
  93013. _this.meshesNames = meshesNames;
  93014. _this.rootUrl = rootUrl;
  93015. _this.sceneFilename = sceneFilename;
  93016. return _this;
  93017. }
  93018. /**
  93019. * Execute the current task
  93020. * @param scene defines the scene where you want your assets to be loaded
  93021. * @param onSuccess is a callback called when the task is successfully executed
  93022. * @param onError is a callback called if an error occurs
  93023. */
  93024. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93025. var _this = this;
  93026. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93027. _this.loadedMeshes = meshes;
  93028. _this.loadedParticleSystems = particleSystems;
  93029. _this.loadedSkeletons = skeletons;
  93030. onSuccess();
  93031. }, null, function (scene, message, exception) {
  93032. onError(message, exception);
  93033. });
  93034. };
  93035. return MeshAssetTask;
  93036. }(AbstractAssetTask));
  93037. BABYLON.MeshAssetTask = MeshAssetTask;
  93038. /**
  93039. * Define a task used by {BABYLON.AssetsManager} to load text content
  93040. */
  93041. var TextFileAssetTask = /** @class */ (function (_super) {
  93042. __extends(TextFileAssetTask, _super);
  93043. /**
  93044. * Creates a new TextFileAssetTask object
  93045. * @param name defines the name of the task
  93046. * @param url defines the location of the file to load
  93047. */
  93048. function TextFileAssetTask(
  93049. /**
  93050. * Defines the name of the task
  93051. */
  93052. name,
  93053. /**
  93054. * Defines the location of the file to load
  93055. */
  93056. url) {
  93057. var _this = _super.call(this, name) || this;
  93058. _this.name = name;
  93059. _this.url = url;
  93060. return _this;
  93061. }
  93062. /**
  93063. * Execute the current task
  93064. * @param scene defines the scene where you want your assets to be loaded
  93065. * @param onSuccess is a callback called when the task is successfully executed
  93066. * @param onError is a callback called if an error occurs
  93067. */
  93068. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93069. var _this = this;
  93070. scene._loadFile(this.url, function (data) {
  93071. _this.text = data;
  93072. onSuccess();
  93073. }, undefined, false, false, function (request, exception) {
  93074. if (request) {
  93075. onError(request.status + " " + request.statusText, exception);
  93076. }
  93077. });
  93078. };
  93079. return TextFileAssetTask;
  93080. }(AbstractAssetTask));
  93081. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93082. /**
  93083. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93084. */
  93085. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93086. __extends(BinaryFileAssetTask, _super);
  93087. /**
  93088. * Creates a new BinaryFileAssetTask object
  93089. * @param name defines the name of the new task
  93090. * @param url defines the location of the file to load
  93091. */
  93092. function BinaryFileAssetTask(
  93093. /**
  93094. * Defines the name of the task
  93095. */
  93096. name,
  93097. /**
  93098. * Defines the location of the file to load
  93099. */
  93100. url) {
  93101. var _this = _super.call(this, name) || this;
  93102. _this.name = name;
  93103. _this.url = url;
  93104. return _this;
  93105. }
  93106. /**
  93107. * Execute the current task
  93108. * @param scene defines the scene where you want your assets to be loaded
  93109. * @param onSuccess is a callback called when the task is successfully executed
  93110. * @param onError is a callback called if an error occurs
  93111. */
  93112. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93113. var _this = this;
  93114. scene._loadFile(this.url, function (data) {
  93115. _this.data = data;
  93116. onSuccess();
  93117. }, undefined, true, true, function (request, exception) {
  93118. if (request) {
  93119. onError(request.status + " " + request.statusText, exception);
  93120. }
  93121. });
  93122. };
  93123. return BinaryFileAssetTask;
  93124. }(AbstractAssetTask));
  93125. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93126. /**
  93127. * Define a task used by {BABYLON.AssetsManager} to load images
  93128. */
  93129. var ImageAssetTask = /** @class */ (function (_super) {
  93130. __extends(ImageAssetTask, _super);
  93131. /**
  93132. * Creates a new ImageAssetTask
  93133. * @param name defines the name of the task
  93134. * @param url defines the location of the image to load
  93135. */
  93136. function ImageAssetTask(
  93137. /**
  93138. * Defines the name of the task
  93139. */
  93140. name,
  93141. /**
  93142. * Defines the location of the image to load
  93143. */
  93144. url) {
  93145. var _this = _super.call(this, name) || this;
  93146. _this.name = name;
  93147. _this.url = url;
  93148. return _this;
  93149. }
  93150. /**
  93151. * Execute the current task
  93152. * @param scene defines the scene where you want your assets to be loaded
  93153. * @param onSuccess is a callback called when the task is successfully executed
  93154. * @param onError is a callback called if an error occurs
  93155. */
  93156. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93157. var _this = this;
  93158. var img = new Image();
  93159. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93160. img.onload = function () {
  93161. _this.image = img;
  93162. onSuccess();
  93163. };
  93164. img.onerror = function (err) {
  93165. onError("Error loading image", err);
  93166. };
  93167. img.src = this.url;
  93168. };
  93169. return ImageAssetTask;
  93170. }(AbstractAssetTask));
  93171. BABYLON.ImageAssetTask = ImageAssetTask;
  93172. /**
  93173. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93174. */
  93175. var TextureAssetTask = /** @class */ (function (_super) {
  93176. __extends(TextureAssetTask, _super);
  93177. /**
  93178. * Creates a new TextureAssetTask object
  93179. * @param name defines the name of the task
  93180. * @param url defines the location of the file to load
  93181. * @param noMipmap defines if mipmap should not be generated (default is false)
  93182. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93183. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93184. */
  93185. function TextureAssetTask(
  93186. /**
  93187. * Defines the name of the task
  93188. */
  93189. name,
  93190. /**
  93191. * Defines the location of the file to load
  93192. */
  93193. url,
  93194. /**
  93195. * Defines if mipmap should not be generated (default is false)
  93196. */
  93197. noMipmap,
  93198. /**
  93199. * Defines if texture must be inverted on Y axis (default is false)
  93200. */
  93201. invertY,
  93202. /**
  93203. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93204. */
  93205. samplingMode) {
  93206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93207. var _this = _super.call(this, name) || this;
  93208. _this.name = name;
  93209. _this.url = url;
  93210. _this.noMipmap = noMipmap;
  93211. _this.invertY = invertY;
  93212. _this.samplingMode = samplingMode;
  93213. return _this;
  93214. }
  93215. /**
  93216. * Execute the current task
  93217. * @param scene defines the scene where you want your assets to be loaded
  93218. * @param onSuccess is a callback called when the task is successfully executed
  93219. * @param onError is a callback called if an error occurs
  93220. */
  93221. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93222. var onload = function () {
  93223. onSuccess();
  93224. };
  93225. var onerror = function (message, exception) {
  93226. onError(message, exception);
  93227. };
  93228. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93229. };
  93230. return TextureAssetTask;
  93231. }(AbstractAssetTask));
  93232. BABYLON.TextureAssetTask = TextureAssetTask;
  93233. /**
  93234. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93235. */
  93236. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93237. __extends(CubeTextureAssetTask, _super);
  93238. /**
  93239. * Creates a new CubeTextureAssetTask
  93240. * @param name defines the name of the task
  93241. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93242. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93243. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93244. * @param files defines the explicit list of files (undefined by default)
  93245. */
  93246. function CubeTextureAssetTask(
  93247. /**
  93248. * Defines the name of the task
  93249. */
  93250. name,
  93251. /**
  93252. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93253. */
  93254. url,
  93255. /**
  93256. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93257. */
  93258. extensions,
  93259. /**
  93260. * Defines if mipmaps should not be generated (default is false)
  93261. */
  93262. noMipmap,
  93263. /**
  93264. * Defines the explicit list of files (undefined by default)
  93265. */
  93266. files) {
  93267. var _this = _super.call(this, name) || this;
  93268. _this.name = name;
  93269. _this.url = url;
  93270. _this.extensions = extensions;
  93271. _this.noMipmap = noMipmap;
  93272. _this.files = files;
  93273. return _this;
  93274. }
  93275. /**
  93276. * Execute the current task
  93277. * @param scene defines the scene where you want your assets to be loaded
  93278. * @param onSuccess is a callback called when the task is successfully executed
  93279. * @param onError is a callback called if an error occurs
  93280. */
  93281. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93282. var onload = function () {
  93283. onSuccess();
  93284. };
  93285. var onerror = function (message, exception) {
  93286. onError(message, exception);
  93287. };
  93288. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93289. };
  93290. return CubeTextureAssetTask;
  93291. }(AbstractAssetTask));
  93292. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93293. /**
  93294. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93295. */
  93296. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93297. __extends(HDRCubeTextureAssetTask, _super);
  93298. /**
  93299. * Creates a new HDRCubeTextureAssetTask object
  93300. * @param name defines the name of the task
  93301. * @param url defines the location of the file to load
  93302. * @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.
  93303. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93304. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93305. * @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)
  93306. * @param reserved Internal use only
  93307. */
  93308. function HDRCubeTextureAssetTask(
  93309. /**
  93310. * Defines the name of the task
  93311. */
  93312. name,
  93313. /**
  93314. * Defines the location of the file to load
  93315. */
  93316. url,
  93317. /**
  93318. * Defines the desired size (the more it increases the longer the generation will be)
  93319. */
  93320. size,
  93321. /**
  93322. * Defines if mipmaps should not be generated (default is false)
  93323. */
  93324. noMipmap,
  93325. /**
  93326. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93327. */
  93328. generateHarmonics,
  93329. /**
  93330. * 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)
  93331. */
  93332. gammaSpace,
  93333. /**
  93334. * Internal Use Only
  93335. */
  93336. reserved) {
  93337. if (noMipmap === void 0) { noMipmap = false; }
  93338. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93339. if (gammaSpace === void 0) { gammaSpace = false; }
  93340. if (reserved === void 0) { reserved = false; }
  93341. var _this = _super.call(this, name) || this;
  93342. _this.name = name;
  93343. _this.url = url;
  93344. _this.size = size;
  93345. _this.noMipmap = noMipmap;
  93346. _this.generateHarmonics = generateHarmonics;
  93347. _this.gammaSpace = gammaSpace;
  93348. _this.reserved = reserved;
  93349. return _this;
  93350. }
  93351. /**
  93352. * Execute the current task
  93353. * @param scene defines the scene where you want your assets to be loaded
  93354. * @param onSuccess is a callback called when the task is successfully executed
  93355. * @param onError is a callback called if an error occurs
  93356. */
  93357. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93358. var onload = function () {
  93359. onSuccess();
  93360. };
  93361. var onerror = function (message, exception) {
  93362. onError(message, exception);
  93363. };
  93364. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93365. };
  93366. return HDRCubeTextureAssetTask;
  93367. }(AbstractAssetTask));
  93368. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93369. /**
  93370. * This class can be used to easily import assets into a scene
  93371. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93372. */
  93373. var AssetsManager = /** @class */ (function () {
  93374. /**
  93375. * Creates a new AssetsManager
  93376. * @param scene defines the scene to work on
  93377. */
  93378. function AssetsManager(scene) {
  93379. this._isLoading = false;
  93380. this._tasks = new Array();
  93381. this._waitingTasksCount = 0;
  93382. this._totalTasksCount = 0;
  93383. /**
  93384. * Observable called when all tasks are processed
  93385. */
  93386. this.onTaskSuccessObservable = new BABYLON.Observable();
  93387. /**
  93388. * Observable called when a task had an error
  93389. */
  93390. this.onTaskErrorObservable = new BABYLON.Observable();
  93391. /**
  93392. * Observable called when a task is successful
  93393. */
  93394. this.onTasksDoneObservable = new BABYLON.Observable();
  93395. /**
  93396. * Observable called when a task is done (whatever the result is)
  93397. */
  93398. this.onProgressObservable = new BABYLON.Observable();
  93399. /**
  93400. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93401. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93402. */
  93403. this.useDefaultLoadingScreen = true;
  93404. this._scene = scene;
  93405. }
  93406. /**
  93407. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93408. * @param taskName defines the name of the new task
  93409. * @param meshesNames defines the name of meshes to load
  93410. * @param rootUrl defines the root url to use to locate files
  93411. * @param sceneFilename defines the filename of the scene file
  93412. * @returns a new {BABYLON.MeshAssetTask} object
  93413. */
  93414. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93415. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93416. this._tasks.push(task);
  93417. return task;
  93418. };
  93419. /**
  93420. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93421. * @param taskName defines the name of the new task
  93422. * @param url defines the url of the file to load
  93423. * @returns a new {BABYLON.TextFileAssetTask} object
  93424. */
  93425. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93426. var task = new TextFileAssetTask(taskName, url);
  93427. this._tasks.push(task);
  93428. return task;
  93429. };
  93430. /**
  93431. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93432. * @param taskName defines the name of the new task
  93433. * @param url defines the url of the file to load
  93434. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93435. */
  93436. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93437. var task = new BinaryFileAssetTask(taskName, url);
  93438. this._tasks.push(task);
  93439. return task;
  93440. };
  93441. /**
  93442. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93443. * @param taskName defines the name of the new task
  93444. * @param url defines the url of the file to load
  93445. * @returns a new {BABYLON.ImageAssetTask} object
  93446. */
  93447. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93448. var task = new ImageAssetTask(taskName, url);
  93449. this._tasks.push(task);
  93450. return task;
  93451. };
  93452. /**
  93453. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93454. * @param taskName defines the name of the new task
  93455. * @param url defines the url of the file to load
  93456. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93457. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93458. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93459. * @returns a new {BABYLON.TextureAssetTask} object
  93460. */
  93461. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93462. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93463. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93464. this._tasks.push(task);
  93465. return task;
  93466. };
  93467. /**
  93468. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93469. * @param taskName defines the name of the new task
  93470. * @param url defines the url of the file to load
  93471. * @param extensions defines the extension to use to load the cube map (can be null)
  93472. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93473. * @param files defines the list of files to load (can be null)
  93474. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93475. */
  93476. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93477. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93478. this._tasks.push(task);
  93479. return task;
  93480. };
  93481. /**
  93482. *
  93483. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93484. * @param taskName defines the name of the new task
  93485. * @param url defines the url of the file to load
  93486. * @param size defines the size you want for the cubemap (can be null)
  93487. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93488. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93489. * @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)
  93490. * @param reserved Internal use only
  93491. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93492. */
  93493. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93494. if (noMipmap === void 0) { noMipmap = false; }
  93495. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93496. if (gammaSpace === void 0) { gammaSpace = false; }
  93497. if (reserved === void 0) { reserved = false; }
  93498. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93499. this._tasks.push(task);
  93500. return task;
  93501. };
  93502. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93503. var _this = this;
  93504. this._waitingTasksCount--;
  93505. try {
  93506. if (task.taskState === AssetTaskState.DONE) {
  93507. // Let's remove successfull tasks
  93508. BABYLON.Tools.SetImmediate(function () {
  93509. var index = _this._tasks.indexOf(task);
  93510. if (index > -1) {
  93511. _this._tasks.splice(index, 1);
  93512. }
  93513. });
  93514. }
  93515. if (this.onProgress) {
  93516. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93517. }
  93518. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93519. }
  93520. catch (e) {
  93521. BABYLON.Tools.Error("Error running progress callbacks.");
  93522. console.log(e);
  93523. }
  93524. if (this._waitingTasksCount === 0) {
  93525. try {
  93526. if (this.onFinish) {
  93527. this.onFinish(this._tasks);
  93528. }
  93529. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93530. }
  93531. catch (e) {
  93532. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93533. console.log(e);
  93534. }
  93535. this._isLoading = false;
  93536. this._scene.getEngine().hideLoadingUI();
  93537. }
  93538. };
  93539. AssetsManager.prototype._runTask = function (task) {
  93540. var _this = this;
  93541. var done = function () {
  93542. try {
  93543. if (_this.onTaskSuccess) {
  93544. _this.onTaskSuccess(task);
  93545. }
  93546. _this.onTaskSuccessObservable.notifyObservers(task);
  93547. _this._decreaseWaitingTasksCount(task);
  93548. }
  93549. catch (e) {
  93550. error("Error executing task success callbacks", e);
  93551. }
  93552. };
  93553. var error = function (message, exception) {
  93554. task._setErrorObject(message, exception);
  93555. if (_this.onTaskError) {
  93556. _this.onTaskError(task);
  93557. }
  93558. _this.onTaskErrorObservable.notifyObservers(task);
  93559. _this._decreaseWaitingTasksCount(task);
  93560. };
  93561. task.run(this._scene, done, error);
  93562. };
  93563. /**
  93564. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93565. * @return the current instance of the {BABYLON.AssetsManager}
  93566. */
  93567. AssetsManager.prototype.reset = function () {
  93568. this._isLoading = false;
  93569. this._tasks = new Array();
  93570. return this;
  93571. };
  93572. /**
  93573. * Start the loading process
  93574. * @return the current instance of the {BABYLON.AssetsManager}
  93575. */
  93576. AssetsManager.prototype.load = function () {
  93577. if (this._isLoading) {
  93578. return this;
  93579. }
  93580. this._isLoading = true;
  93581. this._waitingTasksCount = this._tasks.length;
  93582. this._totalTasksCount = this._tasks.length;
  93583. if (this._waitingTasksCount === 0) {
  93584. this._isLoading = false;
  93585. if (this.onFinish) {
  93586. this.onFinish(this._tasks);
  93587. }
  93588. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93589. return this;
  93590. }
  93591. if (this.useDefaultLoadingScreen) {
  93592. this._scene.getEngine().displayLoadingUI();
  93593. }
  93594. for (var index = 0; index < this._tasks.length; index++) {
  93595. var task = this._tasks[index];
  93596. this._runTask(task);
  93597. }
  93598. return this;
  93599. };
  93600. return AssetsManager;
  93601. }());
  93602. BABYLON.AssetsManager = AssetsManager;
  93603. })(BABYLON || (BABYLON = {}));
  93604. //# sourceMappingURL=babylon.assetsManager.js.map
  93605. var BABYLON;
  93606. (function (BABYLON) {
  93607. var serializedGeometries = [];
  93608. var serializeGeometry = function (geometry, serializationGeometries) {
  93609. if (serializedGeometries[geometry.id]) {
  93610. return;
  93611. }
  93612. if (geometry.doNotSerialize) {
  93613. return;
  93614. }
  93615. if (geometry instanceof BABYLON.BoxGeometry) {
  93616. serializationGeometries.boxes.push(geometry.serialize());
  93617. }
  93618. else if (geometry instanceof BABYLON.SphereGeometry) {
  93619. serializationGeometries.spheres.push(geometry.serialize());
  93620. }
  93621. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93622. serializationGeometries.cylinders.push(geometry.serialize());
  93623. }
  93624. else if (geometry instanceof BABYLON.TorusGeometry) {
  93625. serializationGeometries.toruses.push(geometry.serialize());
  93626. }
  93627. else if (geometry instanceof BABYLON.GroundGeometry) {
  93628. serializationGeometries.grounds.push(geometry.serialize());
  93629. }
  93630. else if (geometry instanceof BABYLON.Plane) {
  93631. serializationGeometries.planes.push(geometry.serialize());
  93632. }
  93633. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93634. serializationGeometries.torusKnots.push(geometry.serialize());
  93635. }
  93636. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93637. throw new Error("Unknown primitive type");
  93638. }
  93639. else {
  93640. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93641. }
  93642. serializedGeometries[geometry.id] = true;
  93643. };
  93644. var serializeMesh = function (mesh, serializationScene) {
  93645. var serializationObject = {};
  93646. // Geometry
  93647. var geometry = mesh._geometry;
  93648. if (geometry) {
  93649. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93650. // 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
  93651. serializeGeometry(geometry, serializationScene.geometries);
  93652. }
  93653. }
  93654. // Custom
  93655. if (mesh.serialize) {
  93656. mesh.serialize(serializationObject);
  93657. }
  93658. return serializationObject;
  93659. };
  93660. var finalizeSingleMesh = function (mesh, serializationObject) {
  93661. //only works if the mesh is already loaded
  93662. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93663. //serialize material
  93664. if (mesh.material) {
  93665. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93666. serializationObject.materials = serializationObject.materials || [];
  93667. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93668. serializationObject.materials.push(mesh.material.serialize());
  93669. }
  93670. }
  93671. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93672. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93673. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93674. serializationObject.multiMaterials.push(mesh.material.serialize());
  93675. }
  93676. }
  93677. }
  93678. //serialize geometry
  93679. var geometry = mesh._geometry;
  93680. if (geometry) {
  93681. if (!serializationObject.geometries) {
  93682. serializationObject.geometries = {};
  93683. serializationObject.geometries.boxes = [];
  93684. serializationObject.geometries.spheres = [];
  93685. serializationObject.geometries.cylinders = [];
  93686. serializationObject.geometries.toruses = [];
  93687. serializationObject.geometries.grounds = [];
  93688. serializationObject.geometries.planes = [];
  93689. serializationObject.geometries.torusKnots = [];
  93690. serializationObject.geometries.vertexData = [];
  93691. }
  93692. serializeGeometry(geometry, serializationObject.geometries);
  93693. }
  93694. // Skeletons
  93695. if (mesh.skeleton) {
  93696. serializationObject.skeletons = serializationObject.skeletons || [];
  93697. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93698. }
  93699. //serialize the actual mesh
  93700. serializationObject.meshes = serializationObject.meshes || [];
  93701. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93702. }
  93703. };
  93704. var SceneSerializer = /** @class */ (function () {
  93705. function SceneSerializer() {
  93706. }
  93707. SceneSerializer.ClearCache = function () {
  93708. serializedGeometries = [];
  93709. };
  93710. SceneSerializer.Serialize = function (scene) {
  93711. var serializationObject = {};
  93712. SceneSerializer.ClearCache();
  93713. // Scene
  93714. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93715. serializationObject.autoClear = scene.autoClear;
  93716. serializationObject.clearColor = scene.clearColor.asArray();
  93717. serializationObject.ambientColor = scene.ambientColor.asArray();
  93718. serializationObject.gravity = scene.gravity.asArray();
  93719. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93720. serializationObject.workerCollisions = scene.workerCollisions;
  93721. // Fog
  93722. if (scene.fogMode && scene.fogMode !== 0) {
  93723. serializationObject.fogMode = scene.fogMode;
  93724. serializationObject.fogColor = scene.fogColor.asArray();
  93725. serializationObject.fogStart = scene.fogStart;
  93726. serializationObject.fogEnd = scene.fogEnd;
  93727. serializationObject.fogDensity = scene.fogDensity;
  93728. }
  93729. //Physics
  93730. if (scene.isPhysicsEnabled()) {
  93731. var physicEngine = scene.getPhysicsEngine();
  93732. if (physicEngine) {
  93733. serializationObject.physicsEnabled = true;
  93734. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93735. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93736. }
  93737. }
  93738. // Metadata
  93739. if (scene.metadata) {
  93740. serializationObject.metadata = scene.metadata;
  93741. }
  93742. // Morph targets
  93743. serializationObject.morphTargetManagers = [];
  93744. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93745. var abstractMesh = _a[_i];
  93746. var manager = abstractMesh.morphTargetManager;
  93747. if (manager) {
  93748. serializationObject.morphTargetManagers.push(manager.serialize());
  93749. }
  93750. }
  93751. // Lights
  93752. serializationObject.lights = [];
  93753. var index;
  93754. var light;
  93755. for (index = 0; index < scene.lights.length; index++) {
  93756. light = scene.lights[index];
  93757. if (!light.doNotSerialize) {
  93758. serializationObject.lights.push(light.serialize());
  93759. }
  93760. }
  93761. // Cameras
  93762. serializationObject.cameras = [];
  93763. for (index = 0; index < scene.cameras.length; index++) {
  93764. var camera = scene.cameras[index];
  93765. if (!camera.doNotSerialize) {
  93766. serializationObject.cameras.push(camera.serialize());
  93767. }
  93768. }
  93769. if (scene.activeCamera) {
  93770. serializationObject.activeCameraID = scene.activeCamera.id;
  93771. }
  93772. // Animations
  93773. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93774. // Materials
  93775. serializationObject.materials = [];
  93776. serializationObject.multiMaterials = [];
  93777. var material;
  93778. for (index = 0; index < scene.materials.length; index++) {
  93779. material = scene.materials[index];
  93780. if (!material.doNotSerialize) {
  93781. serializationObject.materials.push(material.serialize());
  93782. }
  93783. }
  93784. // MultiMaterials
  93785. serializationObject.multiMaterials = [];
  93786. for (index = 0; index < scene.multiMaterials.length; index++) {
  93787. var multiMaterial = scene.multiMaterials[index];
  93788. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93789. }
  93790. // Environment texture
  93791. if (scene.environmentTexture) {
  93792. serializationObject.environmentTexture = scene.environmentTexture.name;
  93793. }
  93794. // Skeletons
  93795. serializationObject.skeletons = [];
  93796. for (index = 0; index < scene.skeletons.length; index++) {
  93797. var skeleton = scene.skeletons[index];
  93798. if (!skeleton.doNotSerialize) {
  93799. serializationObject.skeletons.push(skeleton.serialize());
  93800. }
  93801. }
  93802. // Transform nodes
  93803. serializationObject.transformNodes = [];
  93804. for (index = 0; index < scene.transformNodes.length; index++) {
  93805. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93806. }
  93807. // Geometries
  93808. serializationObject.geometries = {};
  93809. serializationObject.geometries.boxes = [];
  93810. serializationObject.geometries.spheres = [];
  93811. serializationObject.geometries.cylinders = [];
  93812. serializationObject.geometries.toruses = [];
  93813. serializationObject.geometries.grounds = [];
  93814. serializationObject.geometries.planes = [];
  93815. serializationObject.geometries.torusKnots = [];
  93816. serializationObject.geometries.vertexData = [];
  93817. serializedGeometries = [];
  93818. var geometries = scene.getGeometries();
  93819. for (index = 0; index < geometries.length; index++) {
  93820. var geometry = geometries[index];
  93821. if (geometry.isReady()) {
  93822. serializeGeometry(geometry, serializationObject.geometries);
  93823. }
  93824. }
  93825. // Meshes
  93826. serializationObject.meshes = [];
  93827. for (index = 0; index < scene.meshes.length; index++) {
  93828. var abstractMesh = scene.meshes[index];
  93829. if (abstractMesh instanceof BABYLON.Mesh) {
  93830. var mesh = abstractMesh;
  93831. if (!mesh.doNotSerialize) {
  93832. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93833. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93834. }
  93835. }
  93836. }
  93837. }
  93838. // Particles Systems
  93839. serializationObject.particleSystems = [];
  93840. for (index = 0; index < scene.particleSystems.length; index++) {
  93841. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93842. }
  93843. // Lens flares
  93844. serializationObject.lensFlareSystems = [];
  93845. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93846. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93847. }
  93848. // Shadows
  93849. serializationObject.shadowGenerators = [];
  93850. for (index = 0; index < scene.lights.length; index++) {
  93851. light = scene.lights[index];
  93852. var shadowGenerator = light.getShadowGenerator();
  93853. if (shadowGenerator) {
  93854. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93855. }
  93856. }
  93857. // Action Manager
  93858. if (scene.actionManager) {
  93859. serializationObject.actions = scene.actionManager.serialize("scene");
  93860. }
  93861. // Audio
  93862. serializationObject.sounds = [];
  93863. for (index = 0; index < scene.soundTracks.length; index++) {
  93864. var soundtrack = scene.soundTracks[index];
  93865. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93866. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93867. }
  93868. }
  93869. // Effect layers
  93870. serializationObject.effectLayers = [];
  93871. for (index = 0; index < scene.effectLayers.length; index++) {
  93872. var layer = scene.effectLayers[index];
  93873. if (layer.serialize) {
  93874. serializationObject.effectLayers.push(layer.serialize());
  93875. }
  93876. }
  93877. return serializationObject;
  93878. };
  93879. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93880. if (withParents === void 0) { withParents = false; }
  93881. if (withChildren === void 0) { withChildren = false; }
  93882. var serializationObject = {};
  93883. SceneSerializer.ClearCache();
  93884. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93885. if (withParents || withChildren) {
  93886. //deliberate for loop! not for each, appended should be processed as well.
  93887. for (var i = 0; i < toSerialize.length; ++i) {
  93888. if (withChildren) {
  93889. toSerialize[i].getDescendants().forEach(function (node) {
  93890. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93891. toSerialize.push(node);
  93892. }
  93893. });
  93894. }
  93895. //make sure the array doesn't contain the object already
  93896. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93897. toSerialize.push(toSerialize[i].parent);
  93898. }
  93899. }
  93900. }
  93901. toSerialize.forEach(function (mesh) {
  93902. finalizeSingleMesh(mesh, serializationObject);
  93903. });
  93904. return serializationObject;
  93905. };
  93906. return SceneSerializer;
  93907. }());
  93908. BABYLON.SceneSerializer = SceneSerializer;
  93909. })(BABYLON || (BABYLON = {}));
  93910. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93911. var BABYLON;
  93912. (function (BABYLON) {
  93913. var ReflectionProbe = /** @class */ (function () {
  93914. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93915. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93916. var _this = this;
  93917. this.name = name;
  93918. this._viewMatrix = BABYLON.Matrix.Identity();
  93919. this._target = BABYLON.Vector3.Zero();
  93920. this._add = BABYLON.Vector3.Zero();
  93921. this._invertYAxis = false;
  93922. this.position = BABYLON.Vector3.Zero();
  93923. this._scene = scene;
  93924. this._scene.reflectionProbes.push(this);
  93925. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93926. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93927. switch (faceIndex) {
  93928. case 0:
  93929. _this._add.copyFromFloats(1, 0, 0);
  93930. break;
  93931. case 1:
  93932. _this._add.copyFromFloats(-1, 0, 0);
  93933. break;
  93934. case 2:
  93935. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93936. break;
  93937. case 3:
  93938. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93939. break;
  93940. case 4:
  93941. _this._add.copyFromFloats(0, 0, 1);
  93942. break;
  93943. case 5:
  93944. _this._add.copyFromFloats(0, 0, -1);
  93945. break;
  93946. }
  93947. if (_this._attachedMesh) {
  93948. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93949. }
  93950. _this.position.addToRef(_this._add, _this._target);
  93951. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93952. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93953. scene._forcedViewPosition = _this.position;
  93954. });
  93955. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93956. scene._forcedViewPosition = null;
  93957. scene.updateTransformMatrix(true);
  93958. });
  93959. if (scene.activeCamera) {
  93960. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93961. }
  93962. }
  93963. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93964. get: function () {
  93965. return this._renderTargetTexture.samples;
  93966. },
  93967. set: function (value) {
  93968. this._renderTargetTexture.samples = value;
  93969. },
  93970. enumerable: true,
  93971. configurable: true
  93972. });
  93973. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93974. get: function () {
  93975. return this._renderTargetTexture.refreshRate;
  93976. },
  93977. set: function (value) {
  93978. this._renderTargetTexture.refreshRate = value;
  93979. },
  93980. enumerable: true,
  93981. configurable: true
  93982. });
  93983. ReflectionProbe.prototype.getScene = function () {
  93984. return this._scene;
  93985. };
  93986. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93987. get: function () {
  93988. return this._renderTargetTexture;
  93989. },
  93990. enumerable: true,
  93991. configurable: true
  93992. });
  93993. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93994. get: function () {
  93995. return this._renderTargetTexture.renderList;
  93996. },
  93997. enumerable: true,
  93998. configurable: true
  93999. });
  94000. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  94001. this._attachedMesh = mesh;
  94002. };
  94003. /**
  94004. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  94005. *
  94006. * @param renderingGroupId The rendering group id corresponding to its index
  94007. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  94008. */
  94009. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  94010. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  94011. };
  94012. ReflectionProbe.prototype.dispose = function () {
  94013. var index = this._scene.reflectionProbes.indexOf(this);
  94014. if (index !== -1) {
  94015. // Remove from the scene if found
  94016. this._scene.reflectionProbes.splice(index, 1);
  94017. }
  94018. if (this._renderTargetTexture) {
  94019. this._renderTargetTexture.dispose();
  94020. this._renderTargetTexture = null;
  94021. }
  94022. };
  94023. return ReflectionProbe;
  94024. }());
  94025. BABYLON.ReflectionProbe = ReflectionProbe;
  94026. })(BABYLON || (BABYLON = {}));
  94027. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94028. var BABYLON;
  94029. (function (BABYLON) {
  94030. var Layer = /** @class */ (function () {
  94031. function Layer(name, imgUrl, scene, isBackground, color) {
  94032. this.name = name;
  94033. this.scale = new BABYLON.Vector2(1, 1);
  94034. this.offset = new BABYLON.Vector2(0, 0);
  94035. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94036. this.layerMask = 0x0FFFFFFF;
  94037. this._vertexBuffers = {};
  94038. // Events
  94039. /**
  94040. * An event triggered when the layer is disposed.
  94041. */
  94042. this.onDisposeObservable = new BABYLON.Observable();
  94043. /**
  94044. * An event triggered before rendering the scene
  94045. */
  94046. this.onBeforeRenderObservable = new BABYLON.Observable();
  94047. /**
  94048. * An event triggered after rendering the scene
  94049. */
  94050. this.onAfterRenderObservable = new BABYLON.Observable();
  94051. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94052. this.isBackground = isBackground === undefined ? true : isBackground;
  94053. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94054. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94055. this._scene.layers.push(this);
  94056. var engine = this._scene.getEngine();
  94057. // VBO
  94058. var vertices = [];
  94059. vertices.push(1, 1);
  94060. vertices.push(-1, 1);
  94061. vertices.push(-1, -1);
  94062. vertices.push(1, -1);
  94063. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94064. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94065. this._createIndexBuffer();
  94066. // Effects
  94067. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94068. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94069. }
  94070. Object.defineProperty(Layer.prototype, "onDispose", {
  94071. set: function (callback) {
  94072. if (this._onDisposeObserver) {
  94073. this.onDisposeObservable.remove(this._onDisposeObserver);
  94074. }
  94075. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94076. },
  94077. enumerable: true,
  94078. configurable: true
  94079. });
  94080. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94081. set: function (callback) {
  94082. if (this._onBeforeRenderObserver) {
  94083. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94084. }
  94085. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94086. },
  94087. enumerable: true,
  94088. configurable: true
  94089. });
  94090. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94091. set: function (callback) {
  94092. if (this._onAfterRenderObserver) {
  94093. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94094. }
  94095. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94096. },
  94097. enumerable: true,
  94098. configurable: true
  94099. });
  94100. Layer.prototype._createIndexBuffer = function () {
  94101. var engine = this._scene.getEngine();
  94102. // Indices
  94103. var indices = [];
  94104. indices.push(0);
  94105. indices.push(1);
  94106. indices.push(2);
  94107. indices.push(0);
  94108. indices.push(2);
  94109. indices.push(3);
  94110. this._indexBuffer = engine.createIndexBuffer(indices);
  94111. };
  94112. Layer.prototype._rebuild = function () {
  94113. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94114. if (vb) {
  94115. vb._rebuild();
  94116. }
  94117. this._createIndexBuffer();
  94118. };
  94119. Layer.prototype.render = function () {
  94120. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94121. // Check
  94122. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94123. return;
  94124. var engine = this._scene.getEngine();
  94125. this.onBeforeRenderObservable.notifyObservers(this);
  94126. // Render
  94127. engine.enableEffect(currentEffect);
  94128. engine.setState(false);
  94129. // Texture
  94130. currentEffect.setTexture("textureSampler", this.texture);
  94131. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94132. // Color
  94133. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94134. // Scale / offset
  94135. currentEffect.setVector2("offset", this.offset);
  94136. currentEffect.setVector2("scale", this.scale);
  94137. // VBOs
  94138. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94139. // Draw order
  94140. if (!this.alphaTest) {
  94141. engine.setAlphaMode(this.alphaBlendingMode);
  94142. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94143. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94144. }
  94145. else {
  94146. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94147. }
  94148. this.onAfterRenderObservable.notifyObservers(this);
  94149. };
  94150. Layer.prototype.dispose = function () {
  94151. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94152. if (vertexBuffer) {
  94153. vertexBuffer.dispose();
  94154. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94155. }
  94156. if (this._indexBuffer) {
  94157. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94158. this._indexBuffer = null;
  94159. }
  94160. if (this.texture) {
  94161. this.texture.dispose();
  94162. this.texture = null;
  94163. }
  94164. // Remove from scene
  94165. var index = this._scene.layers.indexOf(this);
  94166. this._scene.layers.splice(index, 1);
  94167. // Callback
  94168. this.onDisposeObservable.notifyObservers(this);
  94169. this.onDisposeObservable.clear();
  94170. this.onAfterRenderObservable.clear();
  94171. this.onBeforeRenderObservable.clear();
  94172. };
  94173. return Layer;
  94174. }());
  94175. BABYLON.Layer = Layer;
  94176. })(BABYLON || (BABYLON = {}));
  94177. //# sourceMappingURL=babylon.layer.js.map
  94178. var BABYLON;
  94179. (function (BABYLON) {
  94180. var TextureTools = /** @class */ (function () {
  94181. function TextureTools() {
  94182. }
  94183. /**
  94184. * Uses the GPU to create a copy texture rescaled at a given size
  94185. * @param texture Texture to copy from
  94186. * @param width Desired width
  94187. * @param height Desired height
  94188. * @return Generated texture
  94189. */
  94190. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94191. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94192. var scene = texture.getScene();
  94193. var engine = scene.getEngine();
  94194. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94195. rtt.wrapU = texture.wrapU;
  94196. rtt.wrapV = texture.wrapV;
  94197. rtt.uOffset = texture.uOffset;
  94198. rtt.vOffset = texture.vOffset;
  94199. rtt.uScale = texture.uScale;
  94200. rtt.vScale = texture.vScale;
  94201. rtt.uAng = texture.uAng;
  94202. rtt.vAng = texture.vAng;
  94203. rtt.wAng = texture.wAng;
  94204. rtt.coordinatesIndex = texture.coordinatesIndex;
  94205. rtt.level = texture.level;
  94206. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94207. rtt._texture.isReady = false;
  94208. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94209. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94210. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94211. passPostProcess.getEffect().executeWhenCompiled(function () {
  94212. passPostProcess.onApply = function (effect) {
  94213. effect.setTexture("textureSampler", texture);
  94214. };
  94215. var internalTexture = rtt.getInternalTexture();
  94216. if (internalTexture) {
  94217. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94218. engine.unBindFramebuffer(internalTexture);
  94219. rtt.disposeFramebufferObjects();
  94220. passPostProcess.dispose();
  94221. internalTexture.isReady = true;
  94222. }
  94223. });
  94224. return rtt;
  94225. };
  94226. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94227. if (!scene._environmentBRDFTexture) {
  94228. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94229. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94230. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94231. scene._environmentBRDFTexture = texture;
  94232. }
  94233. return scene._environmentBRDFTexture;
  94234. };
  94235. 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=";
  94236. return TextureTools;
  94237. }());
  94238. BABYLON.TextureTools = TextureTools;
  94239. })(BABYLON || (BABYLON = {}));
  94240. //# sourceMappingURL=babylon.textureTools.js.map
  94241. var BABYLON;
  94242. (function (BABYLON) {
  94243. var FramingBehavior = /** @class */ (function () {
  94244. function FramingBehavior() {
  94245. this._mode = FramingBehavior.FitFrustumSidesMode;
  94246. this._radiusScale = 1.0;
  94247. this._positionScale = 0.5;
  94248. this._defaultElevation = 0.3;
  94249. this._elevationReturnTime = 1500;
  94250. this._elevationReturnWaitTime = 1000;
  94251. this._zoomStopsAnimation = false;
  94252. this._framingTime = 1500;
  94253. this._isPointerDown = false;
  94254. this._lastInteractionTime = -Infinity;
  94255. // Framing control
  94256. this._animatables = new Array();
  94257. this._betaIsAnimating = false;
  94258. }
  94259. Object.defineProperty(FramingBehavior.prototype, "name", {
  94260. get: function () {
  94261. return "Framing";
  94262. },
  94263. enumerable: true,
  94264. configurable: true
  94265. });
  94266. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94267. /**
  94268. * Gets current mode used by the behavior.
  94269. */
  94270. get: function () {
  94271. return this._mode;
  94272. },
  94273. /**
  94274. * Sets the current mode used by the behavior
  94275. */
  94276. set: function (mode) {
  94277. this._mode = mode;
  94278. },
  94279. enumerable: true,
  94280. configurable: true
  94281. });
  94282. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94283. /**
  94284. * Gets the scale applied to the radius
  94285. */
  94286. get: function () {
  94287. return this._radiusScale;
  94288. },
  94289. /**
  94290. * Sets the scale applied to the radius (1 by default)
  94291. */
  94292. set: function (radius) {
  94293. this._radiusScale = radius;
  94294. },
  94295. enumerable: true,
  94296. configurable: true
  94297. });
  94298. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94299. /**
  94300. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94301. */
  94302. get: function () {
  94303. return this._positionScale;
  94304. },
  94305. /**
  94306. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94307. */
  94308. set: function (scale) {
  94309. this._positionScale = scale;
  94310. },
  94311. enumerable: true,
  94312. configurable: true
  94313. });
  94314. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94315. /**
  94316. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94317. * behaviour is triggered, in radians.
  94318. */
  94319. get: function () {
  94320. return this._defaultElevation;
  94321. },
  94322. /**
  94323. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94324. * behaviour is triggered, in radians.
  94325. */
  94326. set: function (elevation) {
  94327. this._defaultElevation = elevation;
  94328. },
  94329. enumerable: true,
  94330. configurable: true
  94331. });
  94332. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94333. /**
  94334. * Gets the time (in milliseconds) taken to return to the default beta position.
  94335. * Negative value indicates camera should not return to default.
  94336. */
  94337. get: function () {
  94338. return this._elevationReturnTime;
  94339. },
  94340. /**
  94341. * Sets the time (in milliseconds) taken to return to the default beta position.
  94342. * Negative value indicates camera should not return to default.
  94343. */
  94344. set: function (speed) {
  94345. this._elevationReturnTime = speed;
  94346. },
  94347. enumerable: true,
  94348. configurable: true
  94349. });
  94350. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94351. /**
  94352. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94353. */
  94354. get: function () {
  94355. return this._elevationReturnWaitTime;
  94356. },
  94357. /**
  94358. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94359. */
  94360. set: function (time) {
  94361. this._elevationReturnWaitTime = time;
  94362. },
  94363. enumerable: true,
  94364. configurable: true
  94365. });
  94366. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94367. /**
  94368. * Gets the flag that indicates if user zooming should stop animation.
  94369. */
  94370. get: function () {
  94371. return this._zoomStopsAnimation;
  94372. },
  94373. /**
  94374. * Sets the flag that indicates if user zooming should stop animation.
  94375. */
  94376. set: function (flag) {
  94377. this._zoomStopsAnimation = flag;
  94378. },
  94379. enumerable: true,
  94380. configurable: true
  94381. });
  94382. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94383. /**
  94384. * Gets the transition time when framing the mesh, in milliseconds
  94385. */
  94386. get: function () {
  94387. return this._framingTime;
  94388. },
  94389. /**
  94390. * Sets the transition time when framing the mesh, in milliseconds
  94391. */
  94392. set: function (time) {
  94393. this._framingTime = time;
  94394. },
  94395. enumerable: true,
  94396. configurable: true
  94397. });
  94398. FramingBehavior.prototype.init = function () {
  94399. // Do notihng
  94400. };
  94401. FramingBehavior.prototype.attach = function (camera) {
  94402. var _this = this;
  94403. this._attachedCamera = camera;
  94404. var scene = this._attachedCamera.getScene();
  94405. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94406. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94407. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94408. _this._isPointerDown = true;
  94409. return;
  94410. }
  94411. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94412. _this._isPointerDown = false;
  94413. }
  94414. });
  94415. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94416. if (mesh) {
  94417. _this.zoomOnMesh(mesh);
  94418. }
  94419. });
  94420. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94421. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94422. _this._applyUserInteraction();
  94423. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94424. // back to the default position after a given timeout
  94425. _this._maintainCameraAboveGround();
  94426. });
  94427. };
  94428. FramingBehavior.prototype.detach = function () {
  94429. if (!this._attachedCamera) {
  94430. return;
  94431. }
  94432. var scene = this._attachedCamera.getScene();
  94433. if (this._onPrePointerObservableObserver) {
  94434. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94435. }
  94436. if (this._onAfterCheckInputsObserver) {
  94437. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94438. }
  94439. if (this._onMeshTargetChangedObserver) {
  94440. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94441. }
  94442. this._attachedCamera = null;
  94443. };
  94444. /**
  94445. * Targets the given mesh and updates zoom level accordingly.
  94446. * @param mesh The mesh to target.
  94447. * @param radius Optional. If a cached radius position already exists, overrides default.
  94448. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94449. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94450. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94451. */
  94452. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94453. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94454. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94455. mesh.computeWorldMatrix(true);
  94456. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94457. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94458. };
  94459. /**
  94460. * Targets the given mesh with its children and updates zoom level accordingly.
  94461. * @param mesh The mesh to target.
  94462. * @param radius Optional. If a cached radius position already exists, overrides default.
  94463. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94464. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94465. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94466. */
  94467. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94468. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94469. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94470. mesh.computeWorldMatrix(true);
  94471. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94472. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94473. };
  94474. /**
  94475. * Targets the given meshes with their children and updates zoom level accordingly.
  94476. * @param meshes The mesh to target.
  94477. * @param radius Optional. If a cached radius position already exists, overrides default.
  94478. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94479. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94480. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94481. */
  94482. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94483. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94484. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94485. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94486. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94487. for (var i = 0; i < meshes.length; i++) {
  94488. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94489. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94490. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94491. }
  94492. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94493. };
  94494. /**
  94495. * Targets the given mesh and updates zoom level accordingly.
  94496. * @param mesh The mesh to target.
  94497. * @param radius Optional. If a cached radius position already exists, overrides default.
  94498. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94499. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94500. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94501. */
  94502. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94503. var _this = this;
  94504. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94505. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94506. var zoomTarget;
  94507. if (!this._attachedCamera) {
  94508. return;
  94509. }
  94510. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94511. var bottom = minimumWorld.y;
  94512. var top = maximumWorld.y;
  94513. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94514. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94515. if (focusOnOriginXZ) {
  94516. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94517. }
  94518. else {
  94519. var centerWorld = minimumWorld.add(radiusWorld);
  94520. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94521. }
  94522. if (!this._vectorTransition) {
  94523. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94524. }
  94525. this._betaIsAnimating = true;
  94526. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94527. if (animatable) {
  94528. this._animatables.push(animatable);
  94529. }
  94530. // sets the radius and lower radius bounds
  94531. // Small delta ensures camera is not always at lower zoom limit.
  94532. var radius = 0;
  94533. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94534. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94535. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94536. radius = position;
  94537. }
  94538. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94539. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94540. if (this._attachedCamera.lowerRadiusLimit === null) {
  94541. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94542. }
  94543. }
  94544. // Set sensibilities
  94545. var extend = maximumWorld.subtract(minimumWorld).length();
  94546. this._attachedCamera.panningSensibility = 5000 / extend;
  94547. this._attachedCamera.wheelPrecision = 100 / radius;
  94548. // transition to new radius
  94549. if (!this._radiusTransition) {
  94550. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94551. }
  94552. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94553. _this.stopAllAnimations();
  94554. if (onAnimationEnd) {
  94555. onAnimationEnd();
  94556. }
  94557. if (_this._attachedCamera) {
  94558. _this._attachedCamera.storeState();
  94559. }
  94560. });
  94561. if (animatable) {
  94562. this._animatables.push(animatable);
  94563. }
  94564. };
  94565. /**
  94566. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94567. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94568. * frustum width.
  94569. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94570. * to fully enclose the mesh in the viewing frustum.
  94571. */
  94572. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94573. var size = maximumWorld.subtract(minimumWorld);
  94574. var boxVectorGlobalDiagonal = size.length();
  94575. var frustumSlope = this._getFrustumSlope();
  94576. // Formula for setting distance
  94577. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94578. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94579. // Horizon distance
  94580. var radius = radiusWithoutFraming * this._radiusScale;
  94581. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94582. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94583. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94584. var camera = this._attachedCamera;
  94585. if (!camera) {
  94586. return 0;
  94587. }
  94588. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94589. // Don't exceed the requested limit
  94590. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94591. }
  94592. // Don't exceed the upper radius limit
  94593. if (camera.upperRadiusLimit) {
  94594. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94595. }
  94596. return distance;
  94597. };
  94598. /**
  94599. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94600. * is automatically returned to its default position (expected to be above ground plane).
  94601. */
  94602. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94603. var _this = this;
  94604. if (this._elevationReturnTime < 0) {
  94605. return;
  94606. }
  94607. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94608. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94609. var limitBeta = Math.PI * 0.5;
  94610. // Bring the camera back up if below the ground plane
  94611. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94612. this._betaIsAnimating = true;
  94613. //Transition to new position
  94614. this.stopAllAnimations();
  94615. if (!this._betaTransition) {
  94616. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94617. }
  94618. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94619. _this._clearAnimationLocks();
  94620. _this.stopAllAnimations();
  94621. });
  94622. if (animatabe) {
  94623. this._animatables.push(animatabe);
  94624. }
  94625. }
  94626. };
  94627. /**
  94628. * Returns the frustum slope based on the canvas ratio and camera FOV
  94629. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94630. */
  94631. FramingBehavior.prototype._getFrustumSlope = function () {
  94632. // Calculate the viewport ratio
  94633. // Aspect Ratio is Height/Width.
  94634. var camera = this._attachedCamera;
  94635. if (!camera) {
  94636. return BABYLON.Vector2.Zero();
  94637. }
  94638. var engine = camera.getScene().getEngine();
  94639. var aspectRatio = engine.getAspectRatio(camera);
  94640. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94641. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94642. var frustumSlopeY = Math.tan(camera.fov / 2);
  94643. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94644. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94645. // along the forward vector.
  94646. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94647. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94648. };
  94649. /**
  94650. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94651. */
  94652. FramingBehavior.prototype._clearAnimationLocks = function () {
  94653. this._betaIsAnimating = false;
  94654. };
  94655. /**
  94656. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94657. */
  94658. FramingBehavior.prototype._applyUserInteraction = function () {
  94659. if (this.isUserIsMoving) {
  94660. this._lastInteractionTime = BABYLON.Tools.Now;
  94661. this.stopAllAnimations();
  94662. this._clearAnimationLocks();
  94663. }
  94664. };
  94665. /**
  94666. * Stops and removes all animations that have been applied to the camera
  94667. */
  94668. FramingBehavior.prototype.stopAllAnimations = function () {
  94669. if (this._attachedCamera) {
  94670. this._attachedCamera.animations = [];
  94671. }
  94672. while (this._animatables.length) {
  94673. if (this._animatables[0]) {
  94674. this._animatables[0].onAnimationEnd = null;
  94675. this._animatables[0].stop();
  94676. }
  94677. this._animatables.shift();
  94678. }
  94679. };
  94680. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94681. /**
  94682. * Gets a value indicating if the user is moving the camera
  94683. */
  94684. get: function () {
  94685. if (!this._attachedCamera) {
  94686. return false;
  94687. }
  94688. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94689. this._attachedCamera.inertialBetaOffset !== 0 ||
  94690. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94691. this._attachedCamera.inertialPanningX !== 0 ||
  94692. this._attachedCamera.inertialPanningY !== 0 ||
  94693. this._isPointerDown;
  94694. },
  94695. enumerable: true,
  94696. configurable: true
  94697. });
  94698. /**
  94699. * The easing function used by animations
  94700. */
  94701. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94702. /**
  94703. * The easing mode used by animations
  94704. */
  94705. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94706. // Statics
  94707. /**
  94708. * The camera can move all the way towards the mesh.
  94709. */
  94710. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94711. /**
  94712. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94713. */
  94714. FramingBehavior.FitFrustumSidesMode = 1;
  94715. return FramingBehavior;
  94716. }());
  94717. BABYLON.FramingBehavior = FramingBehavior;
  94718. })(BABYLON || (BABYLON = {}));
  94719. //# sourceMappingURL=babylon.framingBehavior.js.map
  94720. var BABYLON;
  94721. (function (BABYLON) {
  94722. /**
  94723. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94724. */
  94725. var BouncingBehavior = /** @class */ (function () {
  94726. function BouncingBehavior() {
  94727. /**
  94728. * The duration of the animation, in milliseconds
  94729. */
  94730. this.transitionDuration = 450;
  94731. /**
  94732. * Length of the distance animated by the transition when lower radius is reached
  94733. */
  94734. this.lowerRadiusTransitionRange = 2;
  94735. /**
  94736. * Length of the distance animated by the transition when upper radius is reached
  94737. */
  94738. this.upperRadiusTransitionRange = -2;
  94739. this._autoTransitionRange = false;
  94740. // Animations
  94741. this._radiusIsAnimating = false;
  94742. this._radiusBounceTransition = null;
  94743. this._animatables = new Array();
  94744. }
  94745. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94746. get: function () {
  94747. return "Bouncing";
  94748. },
  94749. enumerable: true,
  94750. configurable: true
  94751. });
  94752. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94753. /**
  94754. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94755. */
  94756. get: function () {
  94757. return this._autoTransitionRange;
  94758. },
  94759. /**
  94760. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94761. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94762. */
  94763. set: function (value) {
  94764. var _this = this;
  94765. if (this._autoTransitionRange === value) {
  94766. return;
  94767. }
  94768. this._autoTransitionRange = value;
  94769. var camera = this._attachedCamera;
  94770. if (!camera) {
  94771. return;
  94772. }
  94773. if (value) {
  94774. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94775. if (!mesh) {
  94776. return;
  94777. }
  94778. mesh.computeWorldMatrix(true);
  94779. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94780. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94781. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94782. });
  94783. }
  94784. else if (this._onMeshTargetChangedObserver) {
  94785. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94786. }
  94787. },
  94788. enumerable: true,
  94789. configurable: true
  94790. });
  94791. BouncingBehavior.prototype.init = function () {
  94792. // Do notihng
  94793. };
  94794. BouncingBehavior.prototype.attach = function (camera) {
  94795. var _this = this;
  94796. this._attachedCamera = camera;
  94797. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94798. if (!_this._attachedCamera) {
  94799. return;
  94800. }
  94801. // Add the bounce animation to the lower radius limit
  94802. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94803. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94804. }
  94805. // Add the bounce animation to the upper radius limit
  94806. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94807. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94808. }
  94809. });
  94810. };
  94811. BouncingBehavior.prototype.detach = function () {
  94812. if (!this._attachedCamera) {
  94813. return;
  94814. }
  94815. if (this._onAfterCheckInputsObserver) {
  94816. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94817. }
  94818. if (this._onMeshTargetChangedObserver) {
  94819. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94820. }
  94821. this._attachedCamera = null;
  94822. };
  94823. /**
  94824. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94825. * @param radiusLimit The limit to check against.
  94826. * @return Bool to indicate if at limit.
  94827. */
  94828. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94829. if (!this._attachedCamera) {
  94830. return false;
  94831. }
  94832. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94833. return true;
  94834. }
  94835. return false;
  94836. };
  94837. /**
  94838. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94839. * @param radiusDelta The delta by which to animate to. Can be negative.
  94840. */
  94841. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94842. var _this = this;
  94843. if (!this._attachedCamera) {
  94844. return;
  94845. }
  94846. if (!this._radiusBounceTransition) {
  94847. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94848. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94849. }
  94850. // Prevent zoom until bounce has completed
  94851. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94852. this._attachedCamera.wheelPrecision = Infinity;
  94853. this._attachedCamera.inertialRadiusOffset = 0;
  94854. // Animate to the radius limit
  94855. this.stopAllAnimations();
  94856. this._radiusIsAnimating = true;
  94857. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94858. if (animatable) {
  94859. this._animatables.push(animatable);
  94860. }
  94861. };
  94862. /**
  94863. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94864. */
  94865. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94866. this._radiusIsAnimating = false;
  94867. if (this._attachedCamera) {
  94868. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94869. }
  94870. };
  94871. /**
  94872. * Stops and removes all animations that have been applied to the camera
  94873. */
  94874. BouncingBehavior.prototype.stopAllAnimations = function () {
  94875. if (this._attachedCamera) {
  94876. this._attachedCamera.animations = [];
  94877. }
  94878. while (this._animatables.length) {
  94879. this._animatables[0].onAnimationEnd = null;
  94880. this._animatables[0].stop();
  94881. this._animatables.shift();
  94882. }
  94883. };
  94884. /**
  94885. * The easing function used by animations
  94886. */
  94887. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94888. /**
  94889. * The easing mode used by animations
  94890. */
  94891. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94892. return BouncingBehavior;
  94893. }());
  94894. BABYLON.BouncingBehavior = BouncingBehavior;
  94895. })(BABYLON || (BABYLON = {}));
  94896. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94897. var BABYLON;
  94898. (function (BABYLON) {
  94899. var AutoRotationBehavior = /** @class */ (function () {
  94900. function AutoRotationBehavior() {
  94901. this._zoomStopsAnimation = false;
  94902. this._idleRotationSpeed = 0.05;
  94903. this._idleRotationWaitTime = 2000;
  94904. this._idleRotationSpinupTime = 2000;
  94905. this._isPointerDown = false;
  94906. this._lastFrameTime = null;
  94907. this._lastInteractionTime = -Infinity;
  94908. this._cameraRotationSpeed = 0;
  94909. this._lastFrameRadius = 0;
  94910. }
  94911. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94912. get: function () {
  94913. return "AutoRotation";
  94914. },
  94915. enumerable: true,
  94916. configurable: true
  94917. });
  94918. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94919. /**
  94920. * Gets the flag that indicates if user zooming should stop animation.
  94921. */
  94922. get: function () {
  94923. return this._zoomStopsAnimation;
  94924. },
  94925. /**
  94926. * Sets the flag that indicates if user zooming should stop animation.
  94927. */
  94928. set: function (flag) {
  94929. this._zoomStopsAnimation = flag;
  94930. },
  94931. enumerable: true,
  94932. configurable: true
  94933. });
  94934. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94935. /**
  94936. * Gets the default speed at which the camera rotates around the model.
  94937. */
  94938. get: function () {
  94939. return this._idleRotationSpeed;
  94940. },
  94941. /**
  94942. * Sets the default speed at which the camera rotates around the model.
  94943. */
  94944. set: function (speed) {
  94945. this._idleRotationSpeed = speed;
  94946. },
  94947. enumerable: true,
  94948. configurable: true
  94949. });
  94950. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94951. /**
  94952. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94953. */
  94954. get: function () {
  94955. return this._idleRotationWaitTime;
  94956. },
  94957. /**
  94958. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94959. */
  94960. set: function (time) {
  94961. this._idleRotationWaitTime = time;
  94962. },
  94963. enumerable: true,
  94964. configurable: true
  94965. });
  94966. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94967. /**
  94968. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94969. */
  94970. get: function () {
  94971. return this._idleRotationSpinupTime;
  94972. },
  94973. /**
  94974. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94975. */
  94976. set: function (time) {
  94977. this._idleRotationSpinupTime = time;
  94978. },
  94979. enumerable: true,
  94980. configurable: true
  94981. });
  94982. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94983. /**
  94984. * Gets a value indicating if the camera is currently rotating because of this behavior
  94985. */
  94986. get: function () {
  94987. return Math.abs(this._cameraRotationSpeed) > 0;
  94988. },
  94989. enumerable: true,
  94990. configurable: true
  94991. });
  94992. AutoRotationBehavior.prototype.init = function () {
  94993. // Do notihng
  94994. };
  94995. AutoRotationBehavior.prototype.attach = function (camera) {
  94996. var _this = this;
  94997. this._attachedCamera = camera;
  94998. var scene = this._attachedCamera.getScene();
  94999. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  95000. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  95001. _this._isPointerDown = true;
  95002. return;
  95003. }
  95004. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  95005. _this._isPointerDown = false;
  95006. }
  95007. });
  95008. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  95009. var now = BABYLON.Tools.Now;
  95010. var dt = 0;
  95011. if (_this._lastFrameTime != null) {
  95012. dt = now - _this._lastFrameTime;
  95013. }
  95014. _this._lastFrameTime = now;
  95015. // Stop the animation if there is user interaction and the animation should stop for this interaction
  95016. _this._applyUserInteraction();
  95017. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  95018. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  95019. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  95020. // Step camera rotation by rotation speed
  95021. if (_this._attachedCamera) {
  95022. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  95023. }
  95024. });
  95025. };
  95026. AutoRotationBehavior.prototype.detach = function () {
  95027. if (!this._attachedCamera) {
  95028. return;
  95029. }
  95030. var scene = this._attachedCamera.getScene();
  95031. if (this._onPrePointerObservableObserver) {
  95032. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95033. }
  95034. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95035. this._attachedCamera = null;
  95036. };
  95037. /**
  95038. * Returns true if user is scrolling.
  95039. * @return true if user is scrolling.
  95040. */
  95041. AutoRotationBehavior.prototype._userIsZooming = function () {
  95042. if (!this._attachedCamera) {
  95043. return false;
  95044. }
  95045. return this._attachedCamera.inertialRadiusOffset !== 0;
  95046. };
  95047. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95048. if (!this._attachedCamera) {
  95049. return false;
  95050. }
  95051. var zoomHasHitLimit = false;
  95052. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95053. zoomHasHitLimit = true;
  95054. }
  95055. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95056. this._lastFrameRadius = this._attachedCamera.radius;
  95057. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95058. };
  95059. /**
  95060. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95061. */
  95062. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95063. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95064. this._lastInteractionTime = BABYLON.Tools.Now;
  95065. }
  95066. };
  95067. // Tools
  95068. AutoRotationBehavior.prototype._userIsMoving = function () {
  95069. if (!this._attachedCamera) {
  95070. return false;
  95071. }
  95072. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95073. this._attachedCamera.inertialBetaOffset !== 0 ||
  95074. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95075. this._attachedCamera.inertialPanningX !== 0 ||
  95076. this._attachedCamera.inertialPanningY !== 0 ||
  95077. this._isPointerDown;
  95078. };
  95079. return AutoRotationBehavior;
  95080. }());
  95081. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95082. })(BABYLON || (BABYLON = {}));
  95083. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95084. var BABYLON;
  95085. (function (BABYLON) {
  95086. var NullEngineOptions = /** @class */ (function () {
  95087. function NullEngineOptions() {
  95088. this.renderWidth = 512;
  95089. this.renderHeight = 256;
  95090. this.textureSize = 512;
  95091. this.deterministicLockstep = false;
  95092. this.lockstepMaxSteps = 4;
  95093. }
  95094. return NullEngineOptions;
  95095. }());
  95096. BABYLON.NullEngineOptions = NullEngineOptions;
  95097. /**
  95098. * The null engine class provides support for headless version of babylon.js.
  95099. * This can be used in server side scenario or for testing purposes
  95100. */
  95101. var NullEngine = /** @class */ (function (_super) {
  95102. __extends(NullEngine, _super);
  95103. function NullEngine(options) {
  95104. if (options === void 0) { options = new NullEngineOptions(); }
  95105. var _this = _super.call(this, null) || this;
  95106. if (options.deterministicLockstep === undefined) {
  95107. options.deterministicLockstep = false;
  95108. }
  95109. if (options.lockstepMaxSteps === undefined) {
  95110. options.lockstepMaxSteps = 4;
  95111. }
  95112. _this._options = options;
  95113. // Init caps
  95114. // We consider we are on a webgl1 capable device
  95115. _this._caps = new BABYLON.EngineCapabilities();
  95116. _this._caps.maxTexturesImageUnits = 16;
  95117. _this._caps.maxVertexTextureImageUnits = 16;
  95118. _this._caps.maxTextureSize = 512;
  95119. _this._caps.maxCubemapTextureSize = 512;
  95120. _this._caps.maxRenderTextureSize = 512;
  95121. _this._caps.maxVertexAttribs = 16;
  95122. _this._caps.maxVaryingVectors = 16;
  95123. _this._caps.maxFragmentUniformVectors = 16;
  95124. _this._caps.maxVertexUniformVectors = 16;
  95125. // Extensions
  95126. _this._caps.standardDerivatives = false;
  95127. _this._caps.astc = null;
  95128. _this._caps.s3tc = null;
  95129. _this._caps.pvrtc = null;
  95130. _this._caps.etc1 = null;
  95131. _this._caps.etc2 = null;
  95132. _this._caps.textureAnisotropicFilterExtension = null;
  95133. _this._caps.maxAnisotropy = 0;
  95134. _this._caps.uintIndices = false;
  95135. _this._caps.fragmentDepthSupported = false;
  95136. _this._caps.highPrecisionShaderSupported = true;
  95137. _this._caps.colorBufferFloat = false;
  95138. _this._caps.textureFloat = false;
  95139. _this._caps.textureFloatLinearFiltering = false;
  95140. _this._caps.textureFloatRender = false;
  95141. _this._caps.textureHalfFloat = false;
  95142. _this._caps.textureHalfFloatLinearFiltering = false;
  95143. _this._caps.textureHalfFloatRender = false;
  95144. _this._caps.textureLOD = false;
  95145. _this._caps.drawBuffersExtension = false;
  95146. _this._caps.depthTextureExtension = false;
  95147. _this._caps.vertexArrayObject = false;
  95148. _this._caps.instancedArrays = false;
  95149. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95150. // Wrappers
  95151. if (typeof URL === "undefined") {
  95152. URL = {
  95153. createObjectURL: function () { },
  95154. revokeObjectURL: function () { }
  95155. };
  95156. }
  95157. if (typeof Blob === "undefined") {
  95158. Blob = function () { };
  95159. }
  95160. return _this;
  95161. }
  95162. NullEngine.prototype.isDeterministicLockStep = function () {
  95163. return this._options.deterministicLockstep;
  95164. };
  95165. NullEngine.prototype.getLockstepMaxSteps = function () {
  95166. return this._options.lockstepMaxSteps;
  95167. };
  95168. NullEngine.prototype.getHardwareScalingLevel = function () {
  95169. return 1.0;
  95170. };
  95171. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95172. return {
  95173. capacity: 0,
  95174. references: 1,
  95175. is32Bits: false
  95176. };
  95177. };
  95178. NullEngine.prototype.createIndexBuffer = function (indices) {
  95179. return {
  95180. capacity: 0,
  95181. references: 1,
  95182. is32Bits: false
  95183. };
  95184. };
  95185. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95186. if (stencil === void 0) { stencil = false; }
  95187. };
  95188. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95189. if (useScreen === void 0) { useScreen = false; }
  95190. if (!useScreen && this._currentRenderTarget) {
  95191. return this._currentRenderTarget.width;
  95192. }
  95193. return this._options.renderWidth;
  95194. };
  95195. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95196. if (useScreen === void 0) { useScreen = false; }
  95197. if (!useScreen && this._currentRenderTarget) {
  95198. return this._currentRenderTarget.height;
  95199. }
  95200. return this._options.renderHeight;
  95201. };
  95202. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95203. this._cachedViewport = viewport;
  95204. };
  95205. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95206. return {
  95207. transformFeedback: null,
  95208. __SPECTOR_rebuildProgram: null
  95209. };
  95210. };
  95211. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95212. return [];
  95213. };
  95214. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95215. return [];
  95216. };
  95217. NullEngine.prototype.bindSamplers = function (effect) {
  95218. this._currentEffect = null;
  95219. };
  95220. NullEngine.prototype.enableEffect = function (effect) {
  95221. this._currentEffect = effect;
  95222. if (effect.onBind) {
  95223. effect.onBind(effect);
  95224. }
  95225. effect.onBindObservable.notifyObservers(effect);
  95226. };
  95227. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95228. if (zOffset === void 0) { zOffset = 0; }
  95229. if (reverseSide === void 0) { reverseSide = false; }
  95230. };
  95231. NullEngine.prototype.setIntArray = function (uniform, array) {
  95232. };
  95233. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95234. };
  95235. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95236. };
  95237. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95238. };
  95239. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95240. };
  95241. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95242. };
  95243. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95244. };
  95245. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95246. };
  95247. NullEngine.prototype.setArray = function (uniform, array) {
  95248. };
  95249. NullEngine.prototype.setArray2 = function (uniform, array) {
  95250. };
  95251. NullEngine.prototype.setArray3 = function (uniform, array) {
  95252. };
  95253. NullEngine.prototype.setArray4 = function (uniform, array) {
  95254. };
  95255. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95256. };
  95257. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95258. };
  95259. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95260. };
  95261. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95262. };
  95263. NullEngine.prototype.setFloat = function (uniform, value) {
  95264. };
  95265. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95266. };
  95267. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95268. };
  95269. NullEngine.prototype.setBool = function (uniform, bool) {
  95270. };
  95271. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95272. };
  95273. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95274. };
  95275. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95276. };
  95277. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95278. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95279. if (this._alphaMode === mode) {
  95280. return;
  95281. }
  95282. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95283. if (!noDepthWriteChange) {
  95284. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95285. }
  95286. this._alphaMode = mode;
  95287. };
  95288. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95289. };
  95290. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95291. if (this.preventCacheWipeBetweenFrames) {
  95292. return;
  95293. }
  95294. this.resetTextureCache();
  95295. this._currentEffect = null;
  95296. if (bruteForce) {
  95297. this._currentProgram = null;
  95298. this._stencilState.reset();
  95299. this._depthCullingState.reset();
  95300. this._alphaState.reset();
  95301. }
  95302. this._cachedVertexBuffers = null;
  95303. this._cachedIndexBuffer = null;
  95304. this._cachedEffectForVertexBuffers = null;
  95305. };
  95306. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95307. };
  95308. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95309. };
  95310. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95311. };
  95312. NullEngine.prototype._createTexture = function () {
  95313. return {};
  95314. };
  95315. NullEngine.prototype._releaseTexture = function (texture) {
  95316. };
  95317. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95319. if (onLoad === void 0) { onLoad = null; }
  95320. if (onError === void 0) { onError = null; }
  95321. if (buffer === void 0) { buffer = null; }
  95322. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95323. var url = String(urlArg);
  95324. texture.url = url;
  95325. texture.generateMipMaps = !noMipmap;
  95326. texture.samplingMode = samplingMode;
  95327. texture.invertY = invertY;
  95328. texture.baseWidth = this._options.textureSize;
  95329. texture.baseHeight = this._options.textureSize;
  95330. texture.width = this._options.textureSize;
  95331. texture.height = this._options.textureSize;
  95332. if (format) {
  95333. texture.format = format;
  95334. }
  95335. texture.isReady = true;
  95336. if (onLoad) {
  95337. onLoad();
  95338. }
  95339. return texture;
  95340. };
  95341. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95342. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95343. if (options !== undefined && typeof options === "object") {
  95344. fullOptions.generateMipMaps = options.generateMipMaps;
  95345. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95346. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95347. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95348. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95349. }
  95350. else {
  95351. fullOptions.generateMipMaps = options;
  95352. fullOptions.generateDepthBuffer = true;
  95353. fullOptions.generateStencilBuffer = false;
  95354. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95355. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95356. }
  95357. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95358. var width = size.width || size;
  95359. var height = size.height || size;
  95360. texture._depthStencilBuffer = {};
  95361. texture._framebuffer = {};
  95362. texture.baseWidth = width;
  95363. texture.baseHeight = height;
  95364. texture.width = width;
  95365. texture.height = height;
  95366. texture.isReady = true;
  95367. texture.samples = 1;
  95368. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95369. texture.samplingMode = fullOptions.samplingMode;
  95370. texture.type = fullOptions.type;
  95371. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95372. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95373. return texture;
  95374. };
  95375. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95376. texture.samplingMode = samplingMode;
  95377. };
  95378. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95379. if (this._currentRenderTarget) {
  95380. this.unBindFramebuffer(this._currentRenderTarget);
  95381. }
  95382. this._currentRenderTarget = texture;
  95383. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95384. if (this._cachedViewport && !forceFullscreenViewport) {
  95385. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95386. }
  95387. };
  95388. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95389. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95390. this._currentRenderTarget = null;
  95391. if (onBeforeUnbind) {
  95392. if (texture._MSAAFramebuffer) {
  95393. this._currentFramebuffer = texture._framebuffer;
  95394. }
  95395. onBeforeUnbind();
  95396. }
  95397. this._currentFramebuffer = null;
  95398. };
  95399. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95400. var vbo = {
  95401. capacity: 1,
  95402. references: 1,
  95403. is32Bits: false
  95404. };
  95405. return vbo;
  95406. };
  95407. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95408. if (offset === void 0) { offset = 0; }
  95409. };
  95410. /**
  95411. * Updates a dynamic vertex buffer.
  95412. * @param vertexBuffer the vertex buffer to update
  95413. * @param data the data used to update the vertex buffer
  95414. * @param byteOffset the byte offset of the data (optional)
  95415. * @param byteLength the byte length of the data (optional)
  95416. */
  95417. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95418. };
  95419. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95420. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95421. this._boundTexturesCache[this._activeChannel] = texture;
  95422. }
  95423. };
  95424. NullEngine.prototype._bindTexture = function (channel, texture) {
  95425. if (channel < 0) {
  95426. return;
  95427. }
  95428. this._bindTextureDirectly(0, texture);
  95429. };
  95430. NullEngine.prototype._releaseBuffer = function (buffer) {
  95431. buffer.references--;
  95432. if (buffer.references === 0) {
  95433. return true;
  95434. }
  95435. return false;
  95436. };
  95437. NullEngine.prototype.releaseEffects = function () {
  95438. };
  95439. return NullEngine;
  95440. }(BABYLON.Engine));
  95441. BABYLON.NullEngine = NullEngine;
  95442. })(BABYLON || (BABYLON = {}));
  95443. //# sourceMappingURL=babylon.nullEngine.js.map
  95444. var BABYLON;
  95445. (function (BABYLON) {
  95446. /**
  95447. * This class can be used to get instrumentation data from a Babylon engine
  95448. */
  95449. var EngineInstrumentation = /** @class */ (function () {
  95450. function EngineInstrumentation(engine) {
  95451. this.engine = engine;
  95452. this._captureGPUFrameTime = false;
  95453. this._gpuFrameTime = new BABYLON.PerfCounter();
  95454. this._captureShaderCompilationTime = false;
  95455. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95456. // Observers
  95457. this._onBeginFrameObserver = null;
  95458. this._onEndFrameObserver = null;
  95459. this._onBeforeShaderCompilationObserver = null;
  95460. this._onAfterShaderCompilationObserver = null;
  95461. }
  95462. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95463. // Properties
  95464. /**
  95465. * Gets the perf counter used for GPU frame time
  95466. */
  95467. get: function () {
  95468. return this._gpuFrameTime;
  95469. },
  95470. enumerable: true,
  95471. configurable: true
  95472. });
  95473. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95474. /**
  95475. * Gets the GPU frame time capture status
  95476. */
  95477. get: function () {
  95478. return this._captureGPUFrameTime;
  95479. },
  95480. /**
  95481. * Enable or disable the GPU frame time capture
  95482. */
  95483. set: function (value) {
  95484. var _this = this;
  95485. if (value === this._captureGPUFrameTime) {
  95486. return;
  95487. }
  95488. this._captureGPUFrameTime = value;
  95489. if (value) {
  95490. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95491. if (!_this._gpuFrameTimeToken) {
  95492. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95493. }
  95494. });
  95495. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95496. if (!_this._gpuFrameTimeToken) {
  95497. return;
  95498. }
  95499. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95500. if (time > -1) {
  95501. _this._gpuFrameTimeToken = null;
  95502. _this._gpuFrameTime.fetchNewFrame();
  95503. _this._gpuFrameTime.addCount(time, true);
  95504. }
  95505. });
  95506. }
  95507. else {
  95508. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95509. this._onBeginFrameObserver = null;
  95510. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95511. this._onEndFrameObserver = null;
  95512. }
  95513. },
  95514. enumerable: true,
  95515. configurable: true
  95516. });
  95517. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95518. /**
  95519. * Gets the perf counter used for shader compilation time
  95520. */
  95521. get: function () {
  95522. return this._shaderCompilationTime;
  95523. },
  95524. enumerable: true,
  95525. configurable: true
  95526. });
  95527. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95528. /**
  95529. * Gets the shader compilation time capture status
  95530. */
  95531. get: function () {
  95532. return this._captureShaderCompilationTime;
  95533. },
  95534. /**
  95535. * Enable or disable the shader compilation time capture
  95536. */
  95537. set: function (value) {
  95538. var _this = this;
  95539. if (value === this._captureShaderCompilationTime) {
  95540. return;
  95541. }
  95542. this._captureShaderCompilationTime = value;
  95543. if (value) {
  95544. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95545. _this._shaderCompilationTime.fetchNewFrame();
  95546. _this._shaderCompilationTime.beginMonitoring();
  95547. });
  95548. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95549. _this._shaderCompilationTime.endMonitoring();
  95550. });
  95551. }
  95552. else {
  95553. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95554. this._onBeforeShaderCompilationObserver = null;
  95555. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95556. this._onAfterShaderCompilationObserver = null;
  95557. }
  95558. },
  95559. enumerable: true,
  95560. configurable: true
  95561. });
  95562. EngineInstrumentation.prototype.dispose = function () {
  95563. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95564. this._onBeginFrameObserver = null;
  95565. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95566. this._onEndFrameObserver = null;
  95567. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95568. this._onBeforeShaderCompilationObserver = null;
  95569. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95570. this._onAfterShaderCompilationObserver = null;
  95571. this.engine = null;
  95572. };
  95573. return EngineInstrumentation;
  95574. }());
  95575. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95576. })(BABYLON || (BABYLON = {}));
  95577. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95578. var BABYLON;
  95579. (function (BABYLON) {
  95580. /**
  95581. * This class can be used to get instrumentation data from a Babylon engine
  95582. */
  95583. var SceneInstrumentation = /** @class */ (function () {
  95584. function SceneInstrumentation(scene) {
  95585. var _this = this;
  95586. this.scene = scene;
  95587. this._captureActiveMeshesEvaluationTime = false;
  95588. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95589. this._captureRenderTargetsRenderTime = false;
  95590. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95591. this._captureFrameTime = false;
  95592. this._frameTime = new BABYLON.PerfCounter();
  95593. this._captureRenderTime = false;
  95594. this._renderTime = new BABYLON.PerfCounter();
  95595. this._captureInterFrameTime = false;
  95596. this._interFrameTime = new BABYLON.PerfCounter();
  95597. this._captureParticlesRenderTime = false;
  95598. this._particlesRenderTime = new BABYLON.PerfCounter();
  95599. this._captureSpritesRenderTime = false;
  95600. this._spritesRenderTime = new BABYLON.PerfCounter();
  95601. this._capturePhysicsTime = false;
  95602. this._physicsTime = new BABYLON.PerfCounter();
  95603. this._captureAnimationsTime = false;
  95604. this._animationsTime = new BABYLON.PerfCounter();
  95605. // Observers
  95606. this._onBeforeActiveMeshesEvaluationObserver = null;
  95607. this._onAfterActiveMeshesEvaluationObserver = null;
  95608. this._onBeforeRenderTargetsRenderObserver = null;
  95609. this._onAfterRenderTargetsRenderObserver = null;
  95610. this._onAfterRenderObserver = null;
  95611. this._onBeforeDrawPhaseObserver = null;
  95612. this._onAfterDrawPhaseObserver = null;
  95613. this._onBeforeAnimationsObserver = null;
  95614. this._onBeforeParticlesRenderingObserver = null;
  95615. this._onAfterParticlesRenderingObserver = null;
  95616. this._onBeforeSpritesRenderingObserver = null;
  95617. this._onAfterSpritesRenderingObserver = null;
  95618. this._onBeforePhysicsObserver = null;
  95619. this._onAfterPhysicsObserver = null;
  95620. this._onAfterAnimationsObserver = null;
  95621. // Before render
  95622. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95623. if (_this._captureActiveMeshesEvaluationTime) {
  95624. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95625. }
  95626. if (_this._captureRenderTargetsRenderTime) {
  95627. _this._renderTargetsRenderTime.fetchNewFrame();
  95628. }
  95629. if (_this._captureFrameTime) {
  95630. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95631. _this._frameTime.beginMonitoring();
  95632. }
  95633. if (_this._captureInterFrameTime) {
  95634. _this._interFrameTime.endMonitoring();
  95635. }
  95636. if (_this._captureParticlesRenderTime) {
  95637. _this._particlesRenderTime.fetchNewFrame();
  95638. }
  95639. if (_this._captureSpritesRenderTime) {
  95640. _this._spritesRenderTime.fetchNewFrame();
  95641. }
  95642. if (_this._captureAnimationsTime) {
  95643. _this._animationsTime.beginMonitoring();
  95644. }
  95645. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95646. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95647. });
  95648. // After render
  95649. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95650. if (_this._captureFrameTime) {
  95651. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95652. _this._frameTime.endMonitoring();
  95653. }
  95654. if (_this._captureRenderTime) {
  95655. _this._renderTime.endMonitoring(false);
  95656. }
  95657. if (_this._captureInterFrameTime) {
  95658. _this._interFrameTime.beginMonitoring();
  95659. }
  95660. });
  95661. }
  95662. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95663. // Properties
  95664. /**
  95665. * Gets the perf counter used for active meshes evaluation time
  95666. */
  95667. get: function () {
  95668. return this._activeMeshesEvaluationTime;
  95669. },
  95670. enumerable: true,
  95671. configurable: true
  95672. });
  95673. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95674. /**
  95675. * Gets the active meshes evaluation time capture status
  95676. */
  95677. get: function () {
  95678. return this._captureActiveMeshesEvaluationTime;
  95679. },
  95680. /**
  95681. * Enable or disable the active meshes evaluation time capture
  95682. */
  95683. set: function (value) {
  95684. var _this = this;
  95685. if (value === this._captureActiveMeshesEvaluationTime) {
  95686. return;
  95687. }
  95688. this._captureActiveMeshesEvaluationTime = value;
  95689. if (value) {
  95690. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95691. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95692. _this._activeMeshesEvaluationTime.beginMonitoring();
  95693. });
  95694. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95695. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95696. _this._activeMeshesEvaluationTime.endMonitoring();
  95697. });
  95698. }
  95699. else {
  95700. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95701. this._onBeforeActiveMeshesEvaluationObserver = null;
  95702. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95703. this._onAfterActiveMeshesEvaluationObserver = null;
  95704. }
  95705. },
  95706. enumerable: true,
  95707. configurable: true
  95708. });
  95709. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95710. /**
  95711. * Gets the perf counter used for render targets render time
  95712. */
  95713. get: function () {
  95714. return this._renderTargetsRenderTime;
  95715. },
  95716. enumerable: true,
  95717. configurable: true
  95718. });
  95719. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95720. /**
  95721. * Gets the render targets render time capture status
  95722. */
  95723. get: function () {
  95724. return this._captureRenderTargetsRenderTime;
  95725. },
  95726. /**
  95727. * Enable or disable the render targets render time capture
  95728. */
  95729. set: function (value) {
  95730. var _this = this;
  95731. if (value === this._captureRenderTargetsRenderTime) {
  95732. return;
  95733. }
  95734. this._captureRenderTargetsRenderTime = value;
  95735. if (value) {
  95736. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95737. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95738. _this._renderTargetsRenderTime.beginMonitoring();
  95739. });
  95740. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95741. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95742. _this._renderTargetsRenderTime.endMonitoring(false);
  95743. });
  95744. }
  95745. else {
  95746. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95747. this._onBeforeRenderTargetsRenderObserver = null;
  95748. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95749. this._onAfterRenderTargetsRenderObserver = null;
  95750. }
  95751. },
  95752. enumerable: true,
  95753. configurable: true
  95754. });
  95755. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95756. /**
  95757. * Gets the perf counter used for particles render time
  95758. */
  95759. get: function () {
  95760. return this._particlesRenderTime;
  95761. },
  95762. enumerable: true,
  95763. configurable: true
  95764. });
  95765. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95766. /**
  95767. * Gets the particles render time capture status
  95768. */
  95769. get: function () {
  95770. return this._captureParticlesRenderTime;
  95771. },
  95772. /**
  95773. * Enable or disable the particles render time capture
  95774. */
  95775. set: function (value) {
  95776. var _this = this;
  95777. if (value === this._captureParticlesRenderTime) {
  95778. return;
  95779. }
  95780. this._captureParticlesRenderTime = value;
  95781. if (value) {
  95782. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95783. BABYLON.Tools.StartPerformanceCounter("Particles");
  95784. _this._particlesRenderTime.beginMonitoring();
  95785. });
  95786. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95787. BABYLON.Tools.EndPerformanceCounter("Particles");
  95788. _this._particlesRenderTime.endMonitoring(false);
  95789. });
  95790. }
  95791. else {
  95792. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95793. this._onBeforeParticlesRenderingObserver = null;
  95794. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95795. this._onAfterParticlesRenderingObserver = null;
  95796. }
  95797. },
  95798. enumerable: true,
  95799. configurable: true
  95800. });
  95801. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95802. /**
  95803. * Gets the perf counter used for sprites render time
  95804. */
  95805. get: function () {
  95806. return this._spritesRenderTime;
  95807. },
  95808. enumerable: true,
  95809. configurable: true
  95810. });
  95811. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95812. /**
  95813. * Gets the sprites render time capture status
  95814. */
  95815. get: function () {
  95816. return this._captureSpritesRenderTime;
  95817. },
  95818. /**
  95819. * Enable or disable the sprites render time capture
  95820. */
  95821. set: function (value) {
  95822. var _this = this;
  95823. if (value === this._captureSpritesRenderTime) {
  95824. return;
  95825. }
  95826. this._captureSpritesRenderTime = value;
  95827. if (value) {
  95828. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95829. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95830. _this._spritesRenderTime.beginMonitoring();
  95831. });
  95832. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95833. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95834. _this._spritesRenderTime.endMonitoring(false);
  95835. });
  95836. }
  95837. else {
  95838. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95839. this._onBeforeSpritesRenderingObserver = null;
  95840. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95841. this._onAfterSpritesRenderingObserver = null;
  95842. }
  95843. },
  95844. enumerable: true,
  95845. configurable: true
  95846. });
  95847. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95848. /**
  95849. * Gets the perf counter used for physics time
  95850. */
  95851. get: function () {
  95852. return this._physicsTime;
  95853. },
  95854. enumerable: true,
  95855. configurable: true
  95856. });
  95857. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95858. /**
  95859. * Gets the physics time capture status
  95860. */
  95861. get: function () {
  95862. return this._capturePhysicsTime;
  95863. },
  95864. /**
  95865. * Enable or disable the physics time capture
  95866. */
  95867. set: function (value) {
  95868. var _this = this;
  95869. if (value === this._capturePhysicsTime) {
  95870. return;
  95871. }
  95872. this._capturePhysicsTime = value;
  95873. if (value) {
  95874. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95875. BABYLON.Tools.StartPerformanceCounter("Physics");
  95876. _this._physicsTime.beginMonitoring();
  95877. });
  95878. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95879. BABYLON.Tools.EndPerformanceCounter("Physics");
  95880. _this._physicsTime.endMonitoring();
  95881. });
  95882. }
  95883. else {
  95884. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95885. this._onBeforePhysicsObserver = null;
  95886. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95887. this._onAfterPhysicsObserver = null;
  95888. }
  95889. },
  95890. enumerable: true,
  95891. configurable: true
  95892. });
  95893. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95894. /**
  95895. * Gets the perf counter used for animations time
  95896. */
  95897. get: function () {
  95898. return this._animationsTime;
  95899. },
  95900. enumerable: true,
  95901. configurable: true
  95902. });
  95903. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95904. /**
  95905. * Gets the animations time capture status
  95906. */
  95907. get: function () {
  95908. return this._captureAnimationsTime;
  95909. },
  95910. /**
  95911. * Enable or disable the animations time capture
  95912. */
  95913. set: function (value) {
  95914. var _this = this;
  95915. if (value === this._captureAnimationsTime) {
  95916. return;
  95917. }
  95918. this._captureAnimationsTime = value;
  95919. if (value) {
  95920. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95921. _this._animationsTime.endMonitoring();
  95922. });
  95923. }
  95924. else {
  95925. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95926. this._onAfterAnimationsObserver = null;
  95927. }
  95928. },
  95929. enumerable: true,
  95930. configurable: true
  95931. });
  95932. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95933. /**
  95934. * Gets the perf counter used for frame time capture
  95935. */
  95936. get: function () {
  95937. return this._frameTime;
  95938. },
  95939. enumerable: true,
  95940. configurable: true
  95941. });
  95942. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95943. /**
  95944. * Gets the frame time capture status
  95945. */
  95946. get: function () {
  95947. return this._captureFrameTime;
  95948. },
  95949. /**
  95950. * Enable or disable the frame time capture
  95951. */
  95952. set: function (value) {
  95953. this._captureFrameTime = value;
  95954. },
  95955. enumerable: true,
  95956. configurable: true
  95957. });
  95958. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95959. /**
  95960. * Gets the perf counter used for inter-frames time capture
  95961. */
  95962. get: function () {
  95963. return this._interFrameTime;
  95964. },
  95965. enumerable: true,
  95966. configurable: true
  95967. });
  95968. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95969. /**
  95970. * Gets the inter-frames time capture status
  95971. */
  95972. get: function () {
  95973. return this._captureInterFrameTime;
  95974. },
  95975. /**
  95976. * Enable or disable the inter-frames time capture
  95977. */
  95978. set: function (value) {
  95979. this._captureInterFrameTime = value;
  95980. },
  95981. enumerable: true,
  95982. configurable: true
  95983. });
  95984. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95985. /**
  95986. * Gets the perf counter used for render time capture
  95987. */
  95988. get: function () {
  95989. return this._renderTime;
  95990. },
  95991. enumerable: true,
  95992. configurable: true
  95993. });
  95994. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95995. /**
  95996. * Gets the render time capture status
  95997. */
  95998. get: function () {
  95999. return this._captureRenderTime;
  96000. },
  96001. /**
  96002. * Enable or disable the render time capture
  96003. */
  96004. set: function (value) {
  96005. var _this = this;
  96006. if (value === this._captureRenderTime) {
  96007. return;
  96008. }
  96009. this._captureRenderTime = value;
  96010. if (value) {
  96011. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  96012. _this._renderTime.beginMonitoring();
  96013. BABYLON.Tools.StartPerformanceCounter("Main render");
  96014. });
  96015. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  96016. _this._renderTime.endMonitoring(false);
  96017. BABYLON.Tools.EndPerformanceCounter("Main render");
  96018. });
  96019. }
  96020. else {
  96021. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96022. this._onBeforeDrawPhaseObserver = null;
  96023. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96024. this._onAfterDrawPhaseObserver = null;
  96025. }
  96026. },
  96027. enumerable: true,
  96028. configurable: true
  96029. });
  96030. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96031. /**
  96032. * Gets the perf counter used for draw calls
  96033. */
  96034. get: function () {
  96035. return this.scene.getEngine()._drawCalls;
  96036. },
  96037. enumerable: true,
  96038. configurable: true
  96039. });
  96040. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96041. /**
  96042. * Gets the perf counter used for texture collisions
  96043. */
  96044. get: function () {
  96045. return this.scene.getEngine()._textureCollisions;
  96046. },
  96047. enumerable: true,
  96048. configurable: true
  96049. });
  96050. SceneInstrumentation.prototype.dispose = function () {
  96051. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96052. this._onAfterRenderObserver = null;
  96053. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96054. this._onBeforeActiveMeshesEvaluationObserver = null;
  96055. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96056. this._onAfterActiveMeshesEvaluationObserver = null;
  96057. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96058. this._onBeforeRenderTargetsRenderObserver = null;
  96059. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96060. this._onAfterRenderTargetsRenderObserver = null;
  96061. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96062. this._onBeforeAnimationsObserver = null;
  96063. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96064. this._onBeforeParticlesRenderingObserver = null;
  96065. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96066. this._onAfterParticlesRenderingObserver = null;
  96067. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96068. this._onBeforeSpritesRenderingObserver = null;
  96069. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96070. this._onAfterSpritesRenderingObserver = null;
  96071. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96072. this._onBeforeDrawPhaseObserver = null;
  96073. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96074. this._onAfterDrawPhaseObserver = null;
  96075. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96076. this._onBeforePhysicsObserver = null;
  96077. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96078. this._onAfterPhysicsObserver = null;
  96079. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96080. this._onAfterAnimationsObserver = null;
  96081. this.scene = null;
  96082. };
  96083. return SceneInstrumentation;
  96084. }());
  96085. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96086. })(BABYLON || (BABYLON = {}));
  96087. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96088. var BABYLON;
  96089. (function (BABYLON) {
  96090. /**
  96091. * @hidden
  96092. **/
  96093. var _TimeToken = /** @class */ (function () {
  96094. function _TimeToken() {
  96095. this._timeElapsedQueryEnded = false;
  96096. }
  96097. return _TimeToken;
  96098. }());
  96099. BABYLON._TimeToken = _TimeToken;
  96100. })(BABYLON || (BABYLON = {}));
  96101. //# sourceMappingURL=babylon.timeToken.js.map
  96102. var BABYLON;
  96103. (function (BABYLON) {
  96104. /**
  96105. * Background material defines definition.
  96106. * @hidden Mainly internal Use
  96107. */
  96108. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96109. __extends(BackgroundMaterialDefines, _super);
  96110. /**
  96111. * Constructor of the defines.
  96112. */
  96113. function BackgroundMaterialDefines() {
  96114. var _this = _super.call(this) || this;
  96115. /**
  96116. * True if the diffuse texture is in use.
  96117. */
  96118. _this.DIFFUSE = false;
  96119. /**
  96120. * The direct UV channel to use.
  96121. */
  96122. _this.DIFFUSEDIRECTUV = 0;
  96123. /**
  96124. * True if the diffuse texture is in gamma space.
  96125. */
  96126. _this.GAMMADIFFUSE = false;
  96127. /**
  96128. * True if the diffuse texture has opacity in the alpha channel.
  96129. */
  96130. _this.DIFFUSEHASALPHA = false;
  96131. /**
  96132. * True if you want the material to fade to transparent at grazing angle.
  96133. */
  96134. _this.OPACITYFRESNEL = false;
  96135. /**
  96136. * True if an extra blur needs to be added in the reflection.
  96137. */
  96138. _this.REFLECTIONBLUR = false;
  96139. /**
  96140. * True if you want the material to fade to reflection at grazing angle.
  96141. */
  96142. _this.REFLECTIONFRESNEL = false;
  96143. /**
  96144. * True if you want the material to falloff as far as you move away from the scene center.
  96145. */
  96146. _this.REFLECTIONFALLOFF = false;
  96147. /**
  96148. * False if the current Webgl implementation does not support the texture lod extension.
  96149. */
  96150. _this.TEXTURELODSUPPORT = false;
  96151. /**
  96152. * True to ensure the data are premultiplied.
  96153. */
  96154. _this.PREMULTIPLYALPHA = false;
  96155. /**
  96156. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96157. */
  96158. _this.USERGBCOLOR = false;
  96159. /**
  96160. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96161. * stays aligned with the desired configuration.
  96162. */
  96163. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96164. /**
  96165. * True to add noise in order to reduce the banding effect.
  96166. */
  96167. _this.NOISE = false;
  96168. /**
  96169. * is the reflection texture in BGR color scheme?
  96170. * Mainly used to solve a bug in ios10 video tag
  96171. */
  96172. _this.REFLECTIONBGR = false;
  96173. _this.IMAGEPROCESSING = false;
  96174. _this.VIGNETTE = false;
  96175. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96176. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96177. _this.TONEMAPPING = false;
  96178. _this.CONTRAST = false;
  96179. _this.COLORCURVES = false;
  96180. _this.COLORGRADING = false;
  96181. _this.COLORGRADING3D = false;
  96182. _this.SAMPLER3DGREENDEPTH = false;
  96183. _this.SAMPLER3DBGRMAP = false;
  96184. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96185. _this.EXPOSURE = false;
  96186. // Reflection.
  96187. _this.REFLECTION = false;
  96188. _this.REFLECTIONMAP_3D = false;
  96189. _this.REFLECTIONMAP_SPHERICAL = false;
  96190. _this.REFLECTIONMAP_PLANAR = false;
  96191. _this.REFLECTIONMAP_CUBIC = false;
  96192. _this.REFLECTIONMAP_PROJECTION = false;
  96193. _this.REFLECTIONMAP_SKYBOX = false;
  96194. _this.REFLECTIONMAP_EXPLICIT = false;
  96195. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96196. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96197. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96198. _this.INVERTCUBICMAP = false;
  96199. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96200. _this.LODINREFLECTIONALPHA = false;
  96201. _this.GAMMAREFLECTION = false;
  96202. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96203. // Default BJS.
  96204. _this.MAINUV1 = false;
  96205. _this.MAINUV2 = false;
  96206. _this.UV1 = false;
  96207. _this.UV2 = false;
  96208. _this.CLIPPLANE = false;
  96209. _this.POINTSIZE = false;
  96210. _this.FOG = false;
  96211. _this.NORMAL = false;
  96212. _this.NUM_BONE_INFLUENCERS = 0;
  96213. _this.BonesPerMesh = 0;
  96214. _this.INSTANCES = false;
  96215. _this.SHADOWFLOAT = false;
  96216. _this.rebuild();
  96217. return _this;
  96218. }
  96219. return BackgroundMaterialDefines;
  96220. }(BABYLON.MaterialDefines));
  96221. /**
  96222. * Background material used to create an efficient environement around your scene.
  96223. */
  96224. var BackgroundMaterial = /** @class */ (function (_super) {
  96225. __extends(BackgroundMaterial, _super);
  96226. /**
  96227. * Instantiates a Background Material in the given scene
  96228. * @param name The friendly name of the material
  96229. * @param scene The scene to add the material to
  96230. */
  96231. function BackgroundMaterial(name, scene) {
  96232. var _this = _super.call(this, name, scene) || this;
  96233. /**
  96234. * Key light Color (multiply against the environement texture)
  96235. */
  96236. _this.primaryColor = BABYLON.Color3.White();
  96237. _this._primaryColorShadowLevel = 0;
  96238. _this._primaryColorHighlightLevel = 0;
  96239. /**
  96240. * Reflection Texture used in the material.
  96241. * Should be author in a specific way for the best result (refer to the documentation).
  96242. */
  96243. _this.reflectionTexture = null;
  96244. /**
  96245. * Reflection Texture level of blur.
  96246. *
  96247. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96248. * texture twice.
  96249. */
  96250. _this.reflectionBlur = 0;
  96251. /**
  96252. * Diffuse Texture used in the material.
  96253. * Should be author in a specific way for the best result (refer to the documentation).
  96254. */
  96255. _this.diffuseTexture = null;
  96256. _this._shadowLights = null;
  96257. /**
  96258. * Specify the list of lights casting shadow on the material.
  96259. * All scene shadow lights will be included if null.
  96260. */
  96261. _this.shadowLights = null;
  96262. /**
  96263. * Helps adjusting the shadow to a softer level if required.
  96264. * 0 means black shadows and 1 means no shadows.
  96265. */
  96266. _this.shadowLevel = 0;
  96267. /**
  96268. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96269. * It is usually zero but might be interesting to modify according to your setup.
  96270. */
  96271. _this.sceneCenter = BABYLON.Vector3.Zero();
  96272. /**
  96273. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96274. * This helps ensuring a nice transition when the camera goes under the ground.
  96275. */
  96276. _this.opacityFresnel = true;
  96277. /**
  96278. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96279. * This helps adding a mirror texture on the ground.
  96280. */
  96281. _this.reflectionFresnel = false;
  96282. /**
  96283. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96284. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96285. */
  96286. _this.reflectionFalloffDistance = 0.0;
  96287. /**
  96288. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96289. */
  96290. _this.reflectionAmount = 1.0;
  96291. /**
  96292. * This specifies the weight of the reflection at grazing angle.
  96293. */
  96294. _this.reflectionReflectance0 = 0.05;
  96295. /**
  96296. * This specifies the weight of the reflection at a perpendicular point of view.
  96297. */
  96298. _this.reflectionReflectance90 = 0.5;
  96299. /**
  96300. * Helps to directly use the maps channels instead of their level.
  96301. */
  96302. _this.useRGBColor = true;
  96303. /**
  96304. * This helps reducing the banding effect that could occur on the background.
  96305. */
  96306. _this.enableNoise = false;
  96307. _this._fovMultiplier = 1.0;
  96308. /**
  96309. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96310. */
  96311. _this.useEquirectangularFOV = false;
  96312. _this._maxSimultaneousLights = 4;
  96313. /**
  96314. * Number of Simultaneous lights allowed on the material.
  96315. */
  96316. _this.maxSimultaneousLights = 4;
  96317. /**
  96318. * Keep track of the image processing observer to allow dispose and replace.
  96319. */
  96320. _this._imageProcessingObserver = null;
  96321. /**
  96322. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96323. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96324. */
  96325. _this.switchToBGR = false;
  96326. // Temp values kept as cache in the material.
  96327. _this._renderTargets = new BABYLON.SmartArray(16);
  96328. _this._reflectionControls = BABYLON.Vector4.Zero();
  96329. _this._white = BABYLON.Color3.White();
  96330. _this._primaryShadowColor = BABYLON.Color3.Black();
  96331. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96332. // Setup the default processing configuration to the scene.
  96333. _this._attachImageProcessingConfiguration(null);
  96334. _this.getRenderTargetTextures = function () {
  96335. _this._renderTargets.reset();
  96336. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96337. _this._renderTargets.push(_this._diffuseTexture);
  96338. }
  96339. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96340. _this._renderTargets.push(_this._reflectionTexture);
  96341. }
  96342. return _this._renderTargets;
  96343. };
  96344. return _this;
  96345. }
  96346. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96347. /**
  96348. * Experimental Internal Use Only.
  96349. *
  96350. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96351. * This acts as a helper to set the primary color to a more "human friendly" value.
  96352. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96353. * output color as close as possible from the chosen value.
  96354. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96355. * part of lighting setup.)
  96356. */
  96357. get: function () {
  96358. return this.__perceptualColor;
  96359. },
  96360. set: function (value) {
  96361. this.__perceptualColor = value;
  96362. this._computePrimaryColorFromPerceptualColor();
  96363. this._markAllSubMeshesAsLightsDirty();
  96364. },
  96365. enumerable: true,
  96366. configurable: true
  96367. });
  96368. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96369. /**
  96370. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96371. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96372. */
  96373. get: function () {
  96374. return this._primaryColorShadowLevel;
  96375. },
  96376. set: function (value) {
  96377. this._primaryColorShadowLevel = value;
  96378. this._computePrimaryColors();
  96379. this._markAllSubMeshesAsLightsDirty();
  96380. },
  96381. enumerable: true,
  96382. configurable: true
  96383. });
  96384. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96385. /**
  96386. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96387. * The primary color is used at the level chosen to define what the white area would look.
  96388. */
  96389. get: function () {
  96390. return this._primaryColorHighlightLevel;
  96391. },
  96392. set: function (value) {
  96393. this._primaryColorHighlightLevel = value;
  96394. this._computePrimaryColors();
  96395. this._markAllSubMeshesAsLightsDirty();
  96396. },
  96397. enumerable: true,
  96398. configurable: true
  96399. });
  96400. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96401. /**
  96402. * Sets the reflection reflectance fresnel values according to the default standard
  96403. * empirically know to work well :-)
  96404. */
  96405. set: function (value) {
  96406. var reflectionWeight = value;
  96407. if (reflectionWeight < 0.5) {
  96408. reflectionWeight = reflectionWeight * 2.0;
  96409. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96410. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96411. }
  96412. else {
  96413. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96414. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96415. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96416. }
  96417. },
  96418. enumerable: true,
  96419. configurable: true
  96420. });
  96421. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96422. /**
  96423. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96424. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96425. * Recommended to be keep at 1.0 except for special cases.
  96426. */
  96427. get: function () {
  96428. return this._fovMultiplier;
  96429. },
  96430. set: function (value) {
  96431. if (isNaN(value)) {
  96432. value = 1.0;
  96433. }
  96434. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96435. },
  96436. enumerable: true,
  96437. configurable: true
  96438. });
  96439. /**
  96440. * Attaches a new image processing configuration to the PBR Material.
  96441. * @param configuration (if null the scene configuration will be use)
  96442. */
  96443. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96444. var _this = this;
  96445. if (configuration === this._imageProcessingConfiguration) {
  96446. return;
  96447. }
  96448. // Detaches observer.
  96449. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96450. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96451. }
  96452. // Pick the scene configuration if needed.
  96453. if (!configuration) {
  96454. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96455. }
  96456. else {
  96457. this._imageProcessingConfiguration = configuration;
  96458. }
  96459. // Attaches observer.
  96460. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96461. _this._computePrimaryColorFromPerceptualColor();
  96462. _this._markAllSubMeshesAsImageProcessingDirty();
  96463. });
  96464. };
  96465. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96466. /**
  96467. * Gets the image processing configuration used either in this material.
  96468. */
  96469. get: function () {
  96470. return this._imageProcessingConfiguration;
  96471. },
  96472. /**
  96473. * Sets the Default image processing configuration used either in the this material.
  96474. *
  96475. * If sets to null, the scene one is in use.
  96476. */
  96477. set: function (value) {
  96478. this._attachImageProcessingConfiguration(value);
  96479. // Ensure the effect will be rebuilt.
  96480. this._markAllSubMeshesAsTexturesDirty();
  96481. },
  96482. enumerable: true,
  96483. configurable: true
  96484. });
  96485. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96486. /**
  96487. * Gets wether the color curves effect is enabled.
  96488. */
  96489. get: function () {
  96490. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96491. },
  96492. /**
  96493. * Sets wether the color curves effect is enabled.
  96494. */
  96495. set: function (value) {
  96496. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96497. },
  96498. enumerable: true,
  96499. configurable: true
  96500. });
  96501. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96502. /**
  96503. * Gets wether the color grading effect is enabled.
  96504. */
  96505. get: function () {
  96506. return this.imageProcessingConfiguration.colorGradingEnabled;
  96507. },
  96508. /**
  96509. * Gets wether the color grading effect is enabled.
  96510. */
  96511. set: function (value) {
  96512. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96513. },
  96514. enumerable: true,
  96515. configurable: true
  96516. });
  96517. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96518. /**
  96519. * Gets wether tonemapping is enabled or not.
  96520. */
  96521. get: function () {
  96522. return this._imageProcessingConfiguration.toneMappingEnabled;
  96523. },
  96524. /**
  96525. * Sets wether tonemapping is enabled or not
  96526. */
  96527. set: function (value) {
  96528. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96529. },
  96530. enumerable: true,
  96531. configurable: true
  96532. });
  96533. ;
  96534. ;
  96535. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96536. /**
  96537. * The camera exposure used on this material.
  96538. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96539. * This corresponds to a photographic exposure.
  96540. */
  96541. get: function () {
  96542. return this._imageProcessingConfiguration.exposure;
  96543. },
  96544. /**
  96545. * The camera exposure used on this material.
  96546. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96547. * This corresponds to a photographic exposure.
  96548. */
  96549. set: function (value) {
  96550. this._imageProcessingConfiguration.exposure = value;
  96551. },
  96552. enumerable: true,
  96553. configurable: true
  96554. });
  96555. ;
  96556. ;
  96557. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96558. /**
  96559. * Gets The camera contrast used on this material.
  96560. */
  96561. get: function () {
  96562. return this._imageProcessingConfiguration.contrast;
  96563. },
  96564. /**
  96565. * Sets The camera contrast used on this material.
  96566. */
  96567. set: function (value) {
  96568. this._imageProcessingConfiguration.contrast = value;
  96569. },
  96570. enumerable: true,
  96571. configurable: true
  96572. });
  96573. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96574. /**
  96575. * Gets the Color Grading 2D Lookup Texture.
  96576. */
  96577. get: function () {
  96578. return this._imageProcessingConfiguration.colorGradingTexture;
  96579. },
  96580. /**
  96581. * Sets the Color Grading 2D Lookup Texture.
  96582. */
  96583. set: function (value) {
  96584. this.imageProcessingConfiguration.colorGradingTexture = value;
  96585. },
  96586. enumerable: true,
  96587. configurable: true
  96588. });
  96589. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96590. /**
  96591. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96592. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96593. * 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;
  96594. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96595. */
  96596. get: function () {
  96597. return this.imageProcessingConfiguration.colorCurves;
  96598. },
  96599. /**
  96600. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96601. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96602. * 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;
  96603. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96604. */
  96605. set: function (value) {
  96606. this.imageProcessingConfiguration.colorCurves = value;
  96607. },
  96608. enumerable: true,
  96609. configurable: true
  96610. });
  96611. /**
  96612. * The entire material has been created in order to prevent overdraw.
  96613. * @returns false
  96614. */
  96615. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96616. return true;
  96617. };
  96618. /**
  96619. * The entire material has been created in order to prevent overdraw.
  96620. * @returns true if blending is enable
  96621. */
  96622. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96623. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96624. };
  96625. /**
  96626. * Checks wether the material is ready to be rendered for a given mesh.
  96627. * @param mesh The mesh to render
  96628. * @param subMesh The submesh to check against
  96629. * @param useInstances Specify wether or not the material is used with instances
  96630. * @returns true if all the dependencies are ready (Textures, Effects...)
  96631. */
  96632. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96633. var _this = this;
  96634. if (useInstances === void 0) { useInstances = false; }
  96635. if (subMesh.effect && this.isFrozen) {
  96636. if (this._wasPreviouslyReady) {
  96637. return true;
  96638. }
  96639. }
  96640. if (!subMesh._materialDefines) {
  96641. subMesh._materialDefines = new BackgroundMaterialDefines();
  96642. }
  96643. var scene = this.getScene();
  96644. var defines = subMesh._materialDefines;
  96645. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96646. if (defines._renderId === scene.getRenderId()) {
  96647. return true;
  96648. }
  96649. }
  96650. var engine = scene.getEngine();
  96651. // Lights
  96652. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96653. defines._needNormals = true;
  96654. // Textures
  96655. if (defines._areTexturesDirty) {
  96656. defines._needUVs = false;
  96657. if (scene.texturesEnabled) {
  96658. if (scene.getEngine().getCaps().textureLOD) {
  96659. defines.TEXTURELODSUPPORT = true;
  96660. }
  96661. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96662. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96663. return false;
  96664. }
  96665. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96666. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96667. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96668. defines.OPACITYFRESNEL = this._opacityFresnel;
  96669. }
  96670. else {
  96671. defines.DIFFUSE = false;
  96672. defines.DIFFUSEHASALPHA = false;
  96673. defines.GAMMADIFFUSE = false;
  96674. defines.OPACITYFRESNEL = false;
  96675. }
  96676. var reflectionTexture = this._reflectionTexture;
  96677. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96678. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96679. return false;
  96680. }
  96681. defines.REFLECTION = true;
  96682. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96683. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96684. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96685. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96686. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96687. defines.REFLECTIONBGR = this.switchToBGR;
  96688. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96689. defines.INVERTCUBICMAP = true;
  96690. }
  96691. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96692. switch (reflectionTexture.coordinatesMode) {
  96693. case BABYLON.Texture.EXPLICIT_MODE:
  96694. defines.REFLECTIONMAP_EXPLICIT = true;
  96695. break;
  96696. case BABYLON.Texture.PLANAR_MODE:
  96697. defines.REFLECTIONMAP_PLANAR = true;
  96698. break;
  96699. case BABYLON.Texture.PROJECTION_MODE:
  96700. defines.REFLECTIONMAP_PROJECTION = true;
  96701. break;
  96702. case BABYLON.Texture.SKYBOX_MODE:
  96703. defines.REFLECTIONMAP_SKYBOX = true;
  96704. break;
  96705. case BABYLON.Texture.SPHERICAL_MODE:
  96706. defines.REFLECTIONMAP_SPHERICAL = true;
  96707. break;
  96708. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96709. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96710. break;
  96711. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96712. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96713. break;
  96714. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96715. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96716. break;
  96717. case BABYLON.Texture.CUBIC_MODE:
  96718. case BABYLON.Texture.INVCUBIC_MODE:
  96719. default:
  96720. defines.REFLECTIONMAP_CUBIC = true;
  96721. break;
  96722. }
  96723. if (this.reflectionFresnel) {
  96724. defines.REFLECTIONFRESNEL = true;
  96725. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96726. this._reflectionControls.x = this.reflectionAmount;
  96727. this._reflectionControls.y = this.reflectionReflectance0;
  96728. this._reflectionControls.z = this.reflectionReflectance90;
  96729. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96730. }
  96731. else {
  96732. defines.REFLECTIONFRESNEL = false;
  96733. defines.REFLECTIONFALLOFF = false;
  96734. }
  96735. }
  96736. else {
  96737. defines.REFLECTION = false;
  96738. defines.REFLECTIONFRESNEL = false;
  96739. defines.REFLECTIONFALLOFF = false;
  96740. defines.REFLECTIONBLUR = false;
  96741. defines.REFLECTIONMAP_3D = false;
  96742. defines.REFLECTIONMAP_SPHERICAL = false;
  96743. defines.REFLECTIONMAP_PLANAR = false;
  96744. defines.REFLECTIONMAP_CUBIC = false;
  96745. defines.REFLECTIONMAP_PROJECTION = false;
  96746. defines.REFLECTIONMAP_SKYBOX = false;
  96747. defines.REFLECTIONMAP_EXPLICIT = false;
  96748. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96749. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96750. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96751. defines.INVERTCUBICMAP = false;
  96752. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96753. defines.LODINREFLECTIONALPHA = false;
  96754. defines.GAMMAREFLECTION = false;
  96755. }
  96756. }
  96757. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96758. defines.USERGBCOLOR = this._useRGBColor;
  96759. defines.NOISE = this._enableNoise;
  96760. }
  96761. if (defines._areLightsDirty) {
  96762. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96763. }
  96764. if (defines._areImageProcessingDirty) {
  96765. if (!this._imageProcessingConfiguration.isReady()) {
  96766. return false;
  96767. }
  96768. this._imageProcessingConfiguration.prepareDefines(defines);
  96769. }
  96770. // Misc.
  96771. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96772. // Values that need to be evaluated on every frame
  96773. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96774. // Attribs
  96775. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96776. if (mesh) {
  96777. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96778. mesh.createNormals(true);
  96779. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96780. }
  96781. }
  96782. }
  96783. // Get correct effect
  96784. if (defines.isDirty) {
  96785. defines.markAsProcessed();
  96786. scene.resetCachedMaterial();
  96787. // Fallbacks
  96788. var fallbacks = new BABYLON.EffectFallbacks();
  96789. if (defines.FOG) {
  96790. fallbacks.addFallback(0, "FOG");
  96791. }
  96792. if (defines.POINTSIZE) {
  96793. fallbacks.addFallback(1, "POINTSIZE");
  96794. }
  96795. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96796. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96797. fallbacks.addCPUSkinningFallback(0, mesh);
  96798. }
  96799. //Attributes
  96800. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96801. if (defines.NORMAL) {
  96802. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96803. }
  96804. if (defines.UV1) {
  96805. attribs.push(BABYLON.VertexBuffer.UVKind);
  96806. }
  96807. if (defines.UV2) {
  96808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96809. }
  96810. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96811. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96812. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96813. "vFogInfos", "vFogColor", "pointSize",
  96814. "vClipPlane", "mBones",
  96815. "vPrimaryColor", "vPrimaryColorShadow",
  96816. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96817. "shadowLevel", "alpha",
  96818. "vBackgroundCenter", "vReflectionControl",
  96819. "vDiffuseInfos", "diffuseMatrix",
  96820. ];
  96821. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96822. var uniformBuffers = ["Material", "Scene"];
  96823. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96824. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96825. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96826. uniformsNames: uniforms,
  96827. uniformBuffersNames: uniformBuffers,
  96828. samplers: samplers,
  96829. defines: defines,
  96830. maxSimultaneousLights: this._maxSimultaneousLights
  96831. });
  96832. var onCompiled = function (effect) {
  96833. if (_this.onCompiled) {
  96834. _this.onCompiled(effect);
  96835. }
  96836. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96837. };
  96838. var join = defines.toString();
  96839. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96840. attributes: attribs,
  96841. uniformsNames: uniforms,
  96842. uniformBuffersNames: uniformBuffers,
  96843. samplers: samplers,
  96844. defines: join,
  96845. fallbacks: fallbacks,
  96846. onCompiled: onCompiled,
  96847. onError: this.onError,
  96848. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96849. }, engine), defines);
  96850. this.buildUniformLayout();
  96851. }
  96852. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96853. return false;
  96854. }
  96855. defines._renderId = scene.getRenderId();
  96856. this._wasPreviouslyReady = true;
  96857. return true;
  96858. };
  96859. /**
  96860. * Compute the primary color according to the chosen perceptual color.
  96861. */
  96862. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96863. if (!this.__perceptualColor) {
  96864. return;
  96865. }
  96866. this._primaryColor.copyFrom(this.__perceptualColor);
  96867. // Revert gamma space.
  96868. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96869. // Revert image processing configuration.
  96870. if (this._imageProcessingConfiguration) {
  96871. // Revert Exposure.
  96872. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96873. }
  96874. this._computePrimaryColors();
  96875. };
  96876. /**
  96877. * Compute the highlights and shadow colors according to their chosen levels.
  96878. */
  96879. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96880. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96881. return;
  96882. }
  96883. // Find the highlight color based on the configuration.
  96884. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96885. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96886. // Find the shadow color based on the configuration.
  96887. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96888. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96889. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96890. };
  96891. /**
  96892. * Build the uniform buffer used in the material.
  96893. */
  96894. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96895. // Order is important !
  96896. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96897. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96898. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96899. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96900. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96901. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96902. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96903. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96904. this._uniformBuffer.addUniform("pointSize", 1);
  96905. this._uniformBuffer.addUniform("shadowLevel", 1);
  96906. this._uniformBuffer.addUniform("alpha", 1);
  96907. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96908. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96909. this._uniformBuffer.create();
  96910. };
  96911. /**
  96912. * Unbind the material.
  96913. */
  96914. BackgroundMaterial.prototype.unbind = function () {
  96915. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96916. this._uniformBuffer.setTexture("diffuseSampler", null);
  96917. }
  96918. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96919. this._uniformBuffer.setTexture("reflectionSampler", null);
  96920. }
  96921. _super.prototype.unbind.call(this);
  96922. };
  96923. /**
  96924. * Bind only the world matrix to the material.
  96925. * @param world The world matrix to bind.
  96926. */
  96927. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96928. this._activeEffect.setMatrix("world", world);
  96929. };
  96930. /**
  96931. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96932. * @param world The world matrix to bind.
  96933. * @param subMesh The submesh to bind for.
  96934. */
  96935. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96936. var scene = this.getScene();
  96937. var defines = subMesh._materialDefines;
  96938. if (!defines) {
  96939. return;
  96940. }
  96941. var effect = subMesh.effect;
  96942. if (!effect) {
  96943. return;
  96944. }
  96945. this._activeEffect = effect;
  96946. // Matrices
  96947. this.bindOnlyWorldMatrix(world);
  96948. // Bones
  96949. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96950. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96951. if (mustRebind) {
  96952. this._uniformBuffer.bindToEffect(effect, "Material");
  96953. this.bindViewProjection(effect);
  96954. var reflectionTexture = this._reflectionTexture;
  96955. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96956. // Texture uniforms
  96957. if (scene.texturesEnabled) {
  96958. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96959. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96960. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96961. }
  96962. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96963. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96964. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96965. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96966. }
  96967. }
  96968. if (this.shadowLevel > 0) {
  96969. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96970. }
  96971. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96972. // Point size
  96973. if (this.pointsCloud) {
  96974. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96975. }
  96976. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96977. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96978. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96979. }
  96980. else {
  96981. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96982. }
  96983. }
  96984. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96985. // Textures
  96986. if (scene.texturesEnabled) {
  96987. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96988. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96989. }
  96990. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96991. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96992. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96993. }
  96994. else if (!defines.REFLECTIONBLUR) {
  96995. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96996. }
  96997. else {
  96998. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96999. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  97000. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  97001. }
  97002. if (defines.REFLECTIONFRESNEL) {
  97003. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  97004. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  97005. }
  97006. }
  97007. }
  97008. // Clip plane
  97009. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  97010. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  97011. }
  97012. if (mustRebind || !this.isFrozen) {
  97013. if (scene.lightsEnabled) {
  97014. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  97015. }
  97016. // View
  97017. this.bindView(effect);
  97018. // Fog
  97019. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  97020. // image processing
  97021. this._imageProcessingConfiguration.bind(this._activeEffect);
  97022. }
  97023. this._uniformBuffer.update();
  97024. this._afterBind(mesh);
  97025. };
  97026. /**
  97027. * Dispose the material.
  97028. * @param forceDisposeEffect Force disposal of the associated effect.
  97029. * @param forceDisposeTextures Force disposal of the associated textures.
  97030. */
  97031. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97032. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97033. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97034. if (forceDisposeTextures) {
  97035. if (this.diffuseTexture) {
  97036. this.diffuseTexture.dispose();
  97037. }
  97038. if (this.reflectionTexture) {
  97039. this.reflectionTexture.dispose();
  97040. }
  97041. }
  97042. this._renderTargets.dispose();
  97043. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97044. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97045. }
  97046. _super.prototype.dispose.call(this, forceDisposeEffect);
  97047. };
  97048. /**
  97049. * Clones the material.
  97050. * @param name The cloned name.
  97051. * @returns The cloned material.
  97052. */
  97053. BackgroundMaterial.prototype.clone = function (name) {
  97054. var _this = this;
  97055. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97056. };
  97057. /**
  97058. * Serializes the current material to its JSON representation.
  97059. * @returns The JSON representation.
  97060. */
  97061. BackgroundMaterial.prototype.serialize = function () {
  97062. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97063. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97064. return serializationObject;
  97065. };
  97066. /**
  97067. * Gets the class name of the material
  97068. * @returns "BackgroundMaterial"
  97069. */
  97070. BackgroundMaterial.prototype.getClassName = function () {
  97071. return "BackgroundMaterial";
  97072. };
  97073. /**
  97074. * Parse a JSON input to create back a background material.
  97075. * @param source The JSON data to parse
  97076. * @param scene The scene to create the parsed material in
  97077. * @param rootUrl The root url of the assets the material depends upon
  97078. * @returns the instantiated BackgroundMaterial.
  97079. */
  97080. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97081. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97082. };
  97083. /**
  97084. * Standard reflectance value at parallel view angle.
  97085. */
  97086. BackgroundMaterial.StandardReflectance0 = 0.05;
  97087. /**
  97088. * Standard reflectance value at grazing angle.
  97089. */
  97090. BackgroundMaterial.StandardReflectance90 = 0.5;
  97091. __decorate([
  97092. BABYLON.serializeAsColor3()
  97093. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97094. __decorate([
  97095. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97096. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97097. __decorate([
  97098. BABYLON.serializeAsColor3()
  97099. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97100. __decorate([
  97101. BABYLON.serialize()
  97102. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97103. __decorate([
  97104. BABYLON.serialize()
  97105. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97106. __decorate([
  97107. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97108. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97109. __decorate([
  97110. BABYLON.serializeAsTexture()
  97111. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97112. __decorate([
  97113. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97114. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97115. __decorate([
  97116. BABYLON.serialize()
  97117. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97118. __decorate([
  97119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97120. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97121. __decorate([
  97122. BABYLON.serializeAsTexture()
  97123. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97124. __decorate([
  97125. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97126. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97127. __decorate([
  97128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97129. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97130. __decorate([
  97131. BABYLON.serialize()
  97132. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97133. __decorate([
  97134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97135. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97136. __decorate([
  97137. BABYLON.serializeAsVector3()
  97138. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97139. __decorate([
  97140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97141. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97142. __decorate([
  97143. BABYLON.serialize()
  97144. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97145. __decorate([
  97146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97147. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97148. __decorate([
  97149. BABYLON.serialize()
  97150. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97151. __decorate([
  97152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97153. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97154. __decorate([
  97155. BABYLON.serialize()
  97156. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97157. __decorate([
  97158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97159. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97160. __decorate([
  97161. BABYLON.serialize()
  97162. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97163. __decorate([
  97164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97165. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97166. __decorate([
  97167. BABYLON.serialize()
  97168. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97169. __decorate([
  97170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97171. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97172. __decorate([
  97173. BABYLON.serialize()
  97174. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97175. __decorate([
  97176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97177. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97178. __decorate([
  97179. BABYLON.serialize()
  97180. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97181. __decorate([
  97182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97183. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97184. __decorate([
  97185. BABYLON.serialize()
  97186. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97187. __decorate([
  97188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97189. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97190. __decorate([
  97191. BABYLON.serialize()
  97192. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97193. __decorate([
  97194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97195. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97196. __decorate([
  97197. BABYLON.serializeAsImageProcessingConfiguration()
  97198. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97199. return BackgroundMaterial;
  97200. }(BABYLON.PushMaterial));
  97201. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97202. })(BABYLON || (BABYLON = {}));
  97203. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97204. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97205. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97206. s = arguments[i];
  97207. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97208. t[p] = s[p];
  97209. }
  97210. return t;
  97211. };
  97212. var BABYLON;
  97213. (function (BABYLON) {
  97214. /**
  97215. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97216. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97217. * It also helps with the default setup of your imageProcessing configuration.
  97218. */
  97219. var EnvironmentHelper = /** @class */ (function () {
  97220. /**
  97221. * constructor
  97222. * @param options
  97223. * @param scene The scene to add the material to
  97224. */
  97225. function EnvironmentHelper(options, scene) {
  97226. var _this = this;
  97227. this._errorHandler = function (message, exception) {
  97228. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97229. };
  97230. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97231. this._scene = scene;
  97232. this.onErrorObservable = new BABYLON.Observable();
  97233. this._setupBackground();
  97234. this._setupImageProcessing();
  97235. }
  97236. /**
  97237. * Creates the default options for the helper.
  97238. */
  97239. EnvironmentHelper._getDefaultOptions = function () {
  97240. return {
  97241. createGround: true,
  97242. groundSize: 15,
  97243. groundTexture: this._groundTextureCDNUrl,
  97244. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97245. groundOpacity: 0.9,
  97246. enableGroundShadow: true,
  97247. groundShadowLevel: 0.5,
  97248. enableGroundMirror: false,
  97249. groundMirrorSizeRatio: 0.3,
  97250. groundMirrorBlurKernel: 64,
  97251. groundMirrorAmount: 1,
  97252. groundMirrorFresnelWeight: 1,
  97253. groundMirrorFallOffDistance: 0,
  97254. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97255. groundYBias: 0.00001,
  97256. createSkybox: true,
  97257. skyboxSize: 20,
  97258. skyboxTexture: this._skyboxTextureCDNUrl,
  97259. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97260. backgroundYRotation: 0,
  97261. sizeAuto: true,
  97262. rootPosition: BABYLON.Vector3.Zero(),
  97263. setupImageProcessing: true,
  97264. environmentTexture: this._environmentTextureCDNUrl,
  97265. cameraExposure: 0.8,
  97266. cameraContrast: 1.2,
  97267. toneMappingEnabled: true,
  97268. };
  97269. };
  97270. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97271. /**
  97272. * Gets the root mesh created by the helper.
  97273. */
  97274. get: function () {
  97275. return this._rootMesh;
  97276. },
  97277. enumerable: true,
  97278. configurable: true
  97279. });
  97280. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97281. /**
  97282. * Gets the skybox created by the helper.
  97283. */
  97284. get: function () {
  97285. return this._skybox;
  97286. },
  97287. enumerable: true,
  97288. configurable: true
  97289. });
  97290. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97291. /**
  97292. * Gets the skybox texture created by the helper.
  97293. */
  97294. get: function () {
  97295. return this._skyboxTexture;
  97296. },
  97297. enumerable: true,
  97298. configurable: true
  97299. });
  97300. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97301. /**
  97302. * Gets the skybox material created by the helper.
  97303. */
  97304. get: function () {
  97305. return this._skyboxMaterial;
  97306. },
  97307. enumerable: true,
  97308. configurable: true
  97309. });
  97310. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97311. /**
  97312. * Gets the ground mesh created by the helper.
  97313. */
  97314. get: function () {
  97315. return this._ground;
  97316. },
  97317. enumerable: true,
  97318. configurable: true
  97319. });
  97320. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97321. /**
  97322. * Gets the ground texture created by the helper.
  97323. */
  97324. get: function () {
  97325. return this._groundTexture;
  97326. },
  97327. enumerable: true,
  97328. configurable: true
  97329. });
  97330. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97331. /**
  97332. * Gets the ground mirror created by the helper.
  97333. */
  97334. get: function () {
  97335. return this._groundMirror;
  97336. },
  97337. enumerable: true,
  97338. configurable: true
  97339. });
  97340. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97341. /**
  97342. * Gets the ground mirror render list to helps pushing the meshes
  97343. * you wish in the ground reflection.
  97344. */
  97345. get: function () {
  97346. if (this._groundMirror) {
  97347. return this._groundMirror.renderList;
  97348. }
  97349. return null;
  97350. },
  97351. enumerable: true,
  97352. configurable: true
  97353. });
  97354. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97355. /**
  97356. * Gets the ground material created by the helper.
  97357. */
  97358. get: function () {
  97359. return this._groundMaterial;
  97360. },
  97361. enumerable: true,
  97362. configurable: true
  97363. });
  97364. /**
  97365. * Updates the background according to the new options
  97366. * @param options
  97367. */
  97368. EnvironmentHelper.prototype.updateOptions = function (options) {
  97369. var newOptions = __assign({}, this._options, options);
  97370. if (this._ground && !newOptions.createGround) {
  97371. this._ground.dispose();
  97372. this._ground = null;
  97373. }
  97374. if (this._groundMaterial && !newOptions.createGround) {
  97375. this._groundMaterial.dispose();
  97376. this._groundMaterial = null;
  97377. }
  97378. if (this._groundTexture) {
  97379. if (this._options.groundTexture != newOptions.groundTexture) {
  97380. this._groundTexture.dispose();
  97381. this._groundTexture = null;
  97382. }
  97383. }
  97384. if (this._skybox && !newOptions.createSkybox) {
  97385. this._skybox.dispose();
  97386. this._skybox = null;
  97387. }
  97388. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97389. this._skyboxMaterial.dispose();
  97390. this._skyboxMaterial = null;
  97391. }
  97392. if (this._skyboxTexture) {
  97393. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97394. this._skyboxTexture.dispose();
  97395. this._skyboxTexture = null;
  97396. }
  97397. }
  97398. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97399. this._groundMirror.dispose();
  97400. this._groundMirror = null;
  97401. }
  97402. if (this._scene.environmentTexture) {
  97403. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97404. this._scene.environmentTexture.dispose();
  97405. }
  97406. }
  97407. this._options = newOptions;
  97408. this._setupBackground();
  97409. this._setupImageProcessing();
  97410. };
  97411. /**
  97412. * Sets the primary color of all the available elements.
  97413. * @param color the main color to affect to the ground and the background
  97414. */
  97415. EnvironmentHelper.prototype.setMainColor = function (color) {
  97416. if (this.groundMaterial) {
  97417. this.groundMaterial.primaryColor = color;
  97418. }
  97419. if (this.skyboxMaterial) {
  97420. this.skyboxMaterial.primaryColor = color;
  97421. }
  97422. if (this.groundMirror) {
  97423. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97424. }
  97425. };
  97426. /**
  97427. * Setup the image processing according to the specified options.
  97428. */
  97429. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97430. if (this._options.setupImageProcessing) {
  97431. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97432. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97433. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97434. this._setupEnvironmentTexture();
  97435. }
  97436. };
  97437. /**
  97438. * Setup the environment texture according to the specified options.
  97439. */
  97440. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97441. if (this._scene.environmentTexture) {
  97442. return;
  97443. }
  97444. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97445. this._scene.environmentTexture = this._options.environmentTexture;
  97446. return;
  97447. }
  97448. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97449. this._scene.environmentTexture = environmentTexture;
  97450. };
  97451. /**
  97452. * Setup the background according to the specified options.
  97453. */
  97454. EnvironmentHelper.prototype._setupBackground = function () {
  97455. if (!this._rootMesh) {
  97456. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97457. }
  97458. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97459. var sceneSize = this._getSceneSize();
  97460. if (this._options.createGround) {
  97461. this._setupGround(sceneSize);
  97462. this._setupGroundMaterial();
  97463. this._setupGroundDiffuseTexture();
  97464. if (this._options.enableGroundMirror) {
  97465. this._setupGroundMirrorTexture(sceneSize);
  97466. }
  97467. this._setupMirrorInGroundMaterial();
  97468. }
  97469. if (this._options.createSkybox) {
  97470. this._setupSkybox(sceneSize);
  97471. this._setupSkyboxMaterial();
  97472. this._setupSkyboxReflectionTexture();
  97473. }
  97474. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97475. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97476. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97477. };
  97478. /**
  97479. * Get the scene sizes according to the setup.
  97480. */
  97481. EnvironmentHelper.prototype._getSceneSize = function () {
  97482. var _this = this;
  97483. var groundSize = this._options.groundSize;
  97484. var skyboxSize = this._options.skyboxSize;
  97485. var rootPosition = this._options.rootPosition;
  97486. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97487. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97488. }
  97489. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97490. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97491. });
  97492. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97493. if (this._options.sizeAuto) {
  97494. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97495. this._scene.activeCamera.upperRadiusLimit) {
  97496. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97497. skyboxSize = groundSize;
  97498. }
  97499. var sceneDiagonalLenght = sceneDiagonal.length();
  97500. if (sceneDiagonalLenght > groundSize) {
  97501. groundSize = sceneDiagonalLenght * 2;
  97502. skyboxSize = groundSize;
  97503. }
  97504. // 10 % bigger.
  97505. groundSize *= 1.1;
  97506. skyboxSize *= 1.5;
  97507. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97508. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97509. }
  97510. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97511. };
  97512. /**
  97513. * Setup the ground according to the specified options.
  97514. */
  97515. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97516. var _this = this;
  97517. if (!this._ground) {
  97518. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97519. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97520. this._ground.parent = this._rootMesh;
  97521. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97522. }
  97523. this._ground.receiveShadows = this._options.enableGroundShadow;
  97524. };
  97525. /**
  97526. * Setup the ground material according to the specified options.
  97527. */
  97528. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97529. if (!this._groundMaterial) {
  97530. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97531. }
  97532. this._groundMaterial.alpha = this._options.groundOpacity;
  97533. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97534. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97535. this._groundMaterial.primaryColor = this._options.groundColor;
  97536. this._groundMaterial.useRGBColor = false;
  97537. this._groundMaterial.enableNoise = true;
  97538. if (this._ground) {
  97539. this._ground.material = this._groundMaterial;
  97540. }
  97541. };
  97542. /**
  97543. * Setup the ground diffuse texture according to the specified options.
  97544. */
  97545. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97546. if (!this._groundMaterial) {
  97547. return;
  97548. }
  97549. if (this._groundTexture) {
  97550. return;
  97551. }
  97552. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97553. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97554. return;
  97555. }
  97556. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97557. diffuseTexture.gammaSpace = false;
  97558. diffuseTexture.hasAlpha = true;
  97559. this._groundMaterial.diffuseTexture = diffuseTexture;
  97560. };
  97561. /**
  97562. * Setup the ground mirror texture according to the specified options.
  97563. */
  97564. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97565. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97566. if (!this._groundMirror) {
  97567. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97568. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97569. this._groundMirror.anisotropicFilteringLevel = 1;
  97570. this._groundMirror.wrapU = wrapping;
  97571. this._groundMirror.wrapV = wrapping;
  97572. this._groundMirror.gammaSpace = false;
  97573. if (this._groundMirror.renderList) {
  97574. for (var i = 0; i < this._scene.meshes.length; i++) {
  97575. var mesh = this._scene.meshes[i];
  97576. if (mesh !== this._ground &&
  97577. mesh !== this._skybox &&
  97578. mesh !== this._rootMesh) {
  97579. this._groundMirror.renderList.push(mesh);
  97580. }
  97581. }
  97582. }
  97583. }
  97584. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97585. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97586. };
  97587. /**
  97588. * Setup the ground to receive the mirror texture.
  97589. */
  97590. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97591. if (this._groundMaterial) {
  97592. this._groundMaterial.reflectionTexture = this._groundMirror;
  97593. this._groundMaterial.reflectionFresnel = true;
  97594. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97595. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97596. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97597. }
  97598. };
  97599. /**
  97600. * Setup the skybox according to the specified options.
  97601. */
  97602. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97603. var _this = this;
  97604. if (!this._skybox) {
  97605. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97606. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97607. }
  97608. this._skybox.parent = this._rootMesh;
  97609. };
  97610. /**
  97611. * Setup the skybox material according to the specified options.
  97612. */
  97613. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97614. if (!this._skybox) {
  97615. return;
  97616. }
  97617. if (!this._skyboxMaterial) {
  97618. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97619. }
  97620. this._skyboxMaterial.useRGBColor = false;
  97621. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97622. this._skyboxMaterial.enableNoise = true;
  97623. this._skybox.material = this._skyboxMaterial;
  97624. };
  97625. /**
  97626. * Setup the skybox reflection texture according to the specified options.
  97627. */
  97628. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97629. if (!this._skyboxMaterial) {
  97630. return;
  97631. }
  97632. if (this._skyboxTexture) {
  97633. return;
  97634. }
  97635. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97636. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97637. return;
  97638. }
  97639. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97640. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97641. this._skyboxTexture.gammaSpace = false;
  97642. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97643. };
  97644. /**
  97645. * Dispose all the elements created by the Helper.
  97646. */
  97647. EnvironmentHelper.prototype.dispose = function () {
  97648. if (this._groundMaterial) {
  97649. this._groundMaterial.dispose(true, true);
  97650. }
  97651. if (this._skyboxMaterial) {
  97652. this._skyboxMaterial.dispose(true, true);
  97653. }
  97654. this._rootMesh.dispose(false);
  97655. };
  97656. /**
  97657. * Default ground texture URL.
  97658. */
  97659. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97660. /**
  97661. * Default skybox texture URL.
  97662. */
  97663. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97664. /**
  97665. * Default environment texture URL.
  97666. */
  97667. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97668. return EnvironmentHelper;
  97669. }());
  97670. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97671. })(BABYLON || (BABYLON = {}));
  97672. //# sourceMappingURL=babylon.environmentHelper.js.map
  97673. var BABYLON;
  97674. (function (BABYLON) {
  97675. /**
  97676. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97677. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97678. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97679. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97680. */
  97681. var VideoDome = /** @class */ (function (_super) {
  97682. __extends(VideoDome, _super);
  97683. /**
  97684. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97685. * @param name Element's name, child elements will append suffixes for their own names.
  97686. * @param urlsOrVideo
  97687. * @param options An object containing optional or exposed sub element properties:
  97688. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97689. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97690. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97691. * @param options **loop=true** Automatically loop video on end.
  97692. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97693. */
  97694. function VideoDome(name, urlsOrVideo, options, scene) {
  97695. var _this = _super.call(this, name, scene) || this;
  97696. // set defaults and manage values
  97697. name = name || "videoDome";
  97698. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97699. options.clickToPlay = Boolean(options.clickToPlay);
  97700. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97701. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97702. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97703. // create
  97704. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97705. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97706. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97707. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97708. flat: false,
  97709. radius: options.size,
  97710. subdivisions: options.resolution,
  97711. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97712. }, scene);
  97713. // configure material
  97714. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97715. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97716. material.reflectionTexture = _this._videoTexture;
  97717. material.useEquirectangularFOV = true;
  97718. material.fovMultiplier = 1.0;
  97719. // configure mesh
  97720. _this._mesh.material = material;
  97721. _this._mesh.parent = _this;
  97722. // optional configuration
  97723. if (options.clickToPlay) {
  97724. scene.onPointerUp = function () {
  97725. _this._videoTexture.video.play();
  97726. };
  97727. }
  97728. return _this;
  97729. }
  97730. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97731. /**
  97732. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97733. * Also see the options.resolution property.
  97734. */
  97735. get: function () {
  97736. return this._material.fovMultiplier;
  97737. },
  97738. set: function (value) {
  97739. this._material.fovMultiplier = value;
  97740. },
  97741. enumerable: true,
  97742. configurable: true
  97743. });
  97744. /**
  97745. * Releases resources associated with this node.
  97746. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97747. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97748. */
  97749. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97750. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97751. this._videoTexture.dispose();
  97752. this._mesh.dispose();
  97753. this._material.dispose();
  97754. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97755. };
  97756. return VideoDome;
  97757. }(BABYLON.Node));
  97758. BABYLON.VideoDome = VideoDome;
  97759. })(BABYLON || (BABYLON = {}));
  97760. //# sourceMappingURL=babylon.videoDome.js.map
  97761. 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\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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*=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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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 vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\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\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\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 vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\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 angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,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;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*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(generalRandoms.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 (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*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,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"};
  97762. 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}","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=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\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=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\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};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97763. globalObject["BABYLON"] = BABYLON;
  97764. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var serializeAsCameraReference = BABYLON.serializeAsCameraReference;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var WorkerPool = BABYLON.WorkerPool;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var DepthTextureCreationOptions = BABYLON.DepthTextureCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationPropertiesOverride = BABYLON.AnimationPropertiesOverride;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var RawTexture3D = BABYLON.RawTexture3D;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var DaydreamController = BABYLON.DaydreamController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var ChromaticAberrationPostProcess = BABYLON.ChromaticAberrationPostProcess;var GrainPostProcess = BABYLON.GrainPostProcess;var SharpenPostProcess = BABYLON.SharpenPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var DepthOfFieldMergePostProcessOptions = BABYLON.DepthOfFieldMergePostProcessOptions;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var BloomMergePostProcess = BABYLON.BloomMergePostProcess;var ExtractHighlightsPostProcess = BABYLON.ExtractHighlightsPostProcess;var BloomEffect = BABYLON.BloomEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;var Space = BABYLON.Space ;var Orientation = BABYLON.Orientation ;var AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation ;var WorkerTaskType = BABYLON.WorkerTaskType ;var WorkerReplyType = BABYLON.WorkerReplyType ;var Xbox360Button = BABYLON.Xbox360Button ;var Xbox360Dpad = BABYLON.Xbox360Dpad ;var PoseEnabledControllerType = BABYLON.PoseEnabledControllerType ;var DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel ;var TonemappingOperator = BABYLON.TonemappingOperator ;var PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff ;var PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode ;var Debug = BABYLON.Debug ;var JoystickAxis = BABYLON.JoystickAxis ;var SimplificationType = BABYLON.SimplificationType ;var AssetTaskState = BABYLON.AssetTaskState ;
  97765. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,serializeAsCameraReference,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,WorkerPool,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,DepthTextureCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationPropertiesOverride,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,RawTexture3D,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,DaydreamController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,ChromaticAberrationPostProcess,GrainPostProcess,SharpenPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,DepthOfFieldMergePostProcessOptions,DepthOfFieldMergePostProcess,CircleOfConfusionPostProcess,DepthOfFieldEffect,BloomMergePostProcess,ExtractHighlightsPostProcess,BloomEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome,Space ,Orientation ,AnimationKeyInterpolation ,WorkerTaskType ,WorkerReplyType ,Xbox360Button ,Xbox360Dpad ,PoseEnabledControllerType ,DepthOfFieldEffectBlurLevel ,TonemappingOperator ,PhysicsRadialImpulseFalloff ,PhysicsUpdraftMode ,Debug ,JoystickAxis ,SimplificationType ,AssetTaskState };